【发布时间】: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