【问题标题】:How to get position of hyperlink tag while parsing DOCX document.xml with PHP?使用 PHP 解析 DOCX document.xml 时如何获取超链接标签的位置?
【发布时间】:2018-10-01 07:49:04
【问题描述】:

我的目标是用 PHP 解析 DOCX 文件以获取所有格式的超链接:

<start of hyperlink(number of the first element of hyperlink in text)>, <end of hyperlink(number of the last element of hyperlink in text)>, <hyperlink text>

例如:

输入:“你好,绝对可怕{adjective: distressing}(you cannot see this in .docx file)world!”

输出: {19, 26, "形容词:令人痛心"}

现在我已经完成了将所有超链接解析为纯文本的代码,但我无法获得其在文本中的位置数。这是我的代码:

define("dir", "Dictations");
define("test_file", "Dictation_Text.docx");

/**
 * @param $filename
 * @return string
 */
function getHyperLinks($filename) {
    $explode_result = explode('.', $filename);
    $extension = end($explode_result);
    if ($extension == "docx") {
        $dataFile = "word/document.xml";
    }
else {
    return "DOCX files only supported";
}
$zip = new ZipArchive;
if ($zip->open($filename) === true) {
    if (($zip_index = $zip->locateName($dataFile)) !== false) {
        $data = $zip->getFromIndex($zip_index);
        $parser = xml_parser_create();
        xml_parse_into_struct($parser, $data, $values, $indexes);
        xml_parser_free($parser);
        $result = Array();
        foreach ($indexes["W:HYPERLINK"] as $ind) {
            if ($values[$ind]["type"] == "open") {
                $result[] = $values[$ind]["attributes"]["W:ANCHOR"];
            }
        }
        return $result;
    }
    else {
        return "File " . $filename . " couldn't be found in " . document;
    }
}
    else {
        return "Couldn't open archive " . $filename;
    }
}

#TODO: getting filename from front by $_GET
$document = dir . "/" . test_file;
$result = getHyperLinks($document);
if (is_array($result)) {
    foreach ($result as $res) {
        echo $res . "\n";
    }
}
else {
    echo $result;
}

所以我找不到任何超链接起始位置的 XML 属性,请告诉我如何获取它或以某种方式从 XMLObject 获取它,或者向我展示另一种更方便的方法来解析 DOCX 文件以获取所有信息我需要。

【问题讨论】:

    标签: php xml hyperlink xml-parsing docx


    【解决方案1】:

    您的方法看起来一般都很好,但您正在查找错误的文件。

    .docx 链接元素不存储在 document.xml 中。很奇怪,对吧?

    word/_rels/document.xml.rels 包含所有这些数据(或 header1.xml.rels 等)。

    如果您想查看格式,请将您的 .docx 重命名为 .zip。然后你可以提取它并查看里面的所有 .xml 文件。每个链接都有一行 XML,因此如果您只需要链接,则可能根本不需要从 document.xml 解析。

    如果您确实需要上下文,您将通过每个关系上的“Id”变量的关联来进行。

    【讨论】:

    • 谢谢,帮了大忙)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2016-12-26
    • 2015-03-26
    相关资源
    最近更新 更多