使用 PHP 解析 pdftk dump_data_fields?

aqu*_*qua 3 php parsing text-parsing pdftk

我需要一些关于dump_data_fields使用 PHP解析 pdftk 给出的输出的最佳方法的建议?

此外,我需要提取的属性是:FieldNameFieldNameAlt以及可选的FieldMaxLengthFieldStateOptions

FieldType: Text
FieldName: TestName1
FieldNameAlt: TestName1
FieldFlags: 29360128
FieldJustification: Left
FieldMaxLength: 5
---
FieldType: Button
FieldName: TestName3
FieldFlags: 0
FieldJustification: Left
FieldStateOption: Off
FieldStateOption: Yes
---
...
Run Code Online (Sandbox Code Playgroud)

mor*_*ido 5

这样的事情就足够了吗?

$handle = fopen("/tmp/bla.txt", "r");
if ($handle) {
    $output = array();
    while (($line = fgets($handle)) !== false) {
        if (trim($line) === "---") {
            // Block completed; process it
            if (sizeof($output) > 0) {
                print_r($output);
            }
            $output = array();
            continue;
        }
        // Process contents of data block
        $parts = explode(":", $line);
        if (sizeof($parts) === 2) {
            $key = trim($parts[0]);
            $value = trim($parts[1]);
            if (isset($output[$key])) {
                $i = 1;
                while(isset($output[$key.$i])) $i++;
                $output[$key.$i] = $value;
            }
            else {
                $output[$key] = $value;
            }
        }
        else {
            // handle malformed input
        }
    }

    // process final block
    if (sizeof($output) > 0) {
        print_r($output);
    }
    fclose($handle);
}
else {
    // error while opening the file
}
Run Code Online (Sandbox Code Playgroud)

这为您提供以下输出:

Array
(
    [FieldType] => Text
    [FieldName] => TestName1
    [FieldNameAlt] => TestName1
    [FieldFlags] => 29360128
    [FieldJustification] => Left
    [FieldMaxLength] => 5
)
Array
(
    [FieldType] => Button
    [FieldName] => TestName3
    [FieldFlags] => 0
    [FieldJustification] => Left
    [FieldStateOption] => Off
    [FieldStateOption1] => Yes
)
Run Code Online (Sandbox Code Playgroud)

找出这些值就像这样简单:

echo $output["FieldName"];
Run Code Online (Sandbox Code Playgroud)