我有一个XML文件( Word文档的一部分),它是非常简单的XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Matter"><vt:lpwstr>30738</vt:lpwstr></property><property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="Document number"><vt:lpwstr>999999</vt:lpwstr></property></Properties>然而,当我用SimpleXML解析它时,我得到了<property>项的所有属性,但不能访问这些值(例如,<vt:lpwstr>999999</vt:lpwstr>)。
$custom = simplexml_load_string($xml);
print_r($custom);
// Results in:
SimpleXMLElement Object
(
[property] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[fmtid] => {D5CDD505-2E9C-101B-9397-08002B2CF9AE}
[pid] => 2
[name] => Matter
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[fmtid] => {D5CDD505-2E9C-101B-9397-08002B2CF9AE}
[pid] => 3
[name] => Document number
)
)
)
)我遗漏了什么?
谢谢!
发布于 2020-09-20 14:22:24
显然,这里的print_r()不会输出带有非默认名称空间的XML节点,例如示例中的lpwstr。
但是您可以使用XPath表达式验证所有节点信息是否可用。三个例子:
代码:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties
xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Matter">
<vt:lpwstr>30738</vt:lpwstr>
</property>
<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="Document number">
<vt:lpwstr>999999</vt:lpwstr>
</property>
</Properties>
XML;
$xmlobj = new SimpleXMLElement($xml);
$lpwstr = $xmlobj->xpath('//vt:lpwstr');
print_r($lpwstr);
$lpwstr = $xmlobj->xpath('//*[local-name()="lpwstr"]');
print_r($lpwstr);
$lpwstr = $xmlobj->xpath('//*');
print_r($lpwstr);
?>输出:
Array
(
[0] => SimpleXMLElement Object
(
[0] => 30738
)
[1] => SimpleXMLElement Object
(
[0] => 999999
)
)
Array
(
[0] => SimpleXMLElement Object
(
[0] => 30738
)
[1] => SimpleXMLElement Object
(
[0] => 999999
)
)
Array
(
[0] => SimpleXMLElement Object
(
[property] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[fmtid] => {D5CDD505-2E9C-101B-9397-08002B2CF9AE}
[pid] => 2
[name] => Matter
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[fmtid] => {D5CDD505-2E9C-101B-9397-08002B2CF9AE}
[pid] => 3
[name] => Document number
)
)
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[fmtid] => {D5CDD505-2E9C-101B-9397-08002B2CF9AE}
[pid] => 2
[name] => Matter
)
)
[2] => SimpleXMLElement Object
(
[0] => 30738
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[fmtid] => {D5CDD505-2E9C-101B-9397-08002B2CF9AE}
[pid] => 3
[name] => Document number
)
)
[4] => SimpleXMLElement Object
(
[0] => 999999
)
)使用PHP 7.3
https://stackoverflow.com/questions/63975436
复制相似问题