我以 xml 形式接收文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Document xmlns="http://adress1" xmlns:adr="http://adress2" xmlns:inst="adress3" xmlns:meta="adress4" xmlns:oso="adress5" xmlns:str="adress6" xmlns:xsi="adress7">
<str:DataDocument>
<str:Head/>
<meta:Date typeDate="created">
<meta:Time>2014-07-23T12:35:20+02:00</meta:Time>
</meta:Date>
</str:DataDocument>
<contentDocument format="text/xml" coding="xml">
<Values>
<Attachments>
<str:Attachment format="text/html" code="base64" nameFile="name.html">
<str:DataAttachment>VALUESRECEIVE</str:DataAttachment>
</str:Attachment>
<str:Attachment format="text/xml" code="base64" nameFile="name.xml">
<str:DataAttachment>VALUESToRECEIVE</str:DataAttachment>
</str:Attachment>
<str:Attachment format="text/xml" code="base64" nameFile="name2.xml">
<str:DataAttachment>VALUESToRECEIVE</str:DataAttachment>
</str:Attachment>
</Attachments>
</Values>
</contentDocument>
(...)
</Document>
我必须接收所有节点:
<str:DataAttachment>
和 <str:DataAttachment>
对于每个 <str:Attachment>
.我写了这个:
$attachment = new SimpleXMLElement(file_get_contents($file1));
//first way
$res = $attachment->xpath('contentDocument/Values/Attachments/*');
//second way
$zalacznikiListFromXml = $attachment->contentDocument->Values->Attachments;
foreach ($attachmentListFromXml as $Attachments){
foreach($Attachmentsas $strAttachment)
$attachToDecode = $strAttachment['str:DataAttachment'];
}
但两者都是
xpath
和 $attachment->contentDocument->Values->Attachments
返回空对象。我不知道有什么问题。你能帮我找到每个 str:DataAttachment 吗?
感谢您的任何帮助。
最佳答案
详细说明@Ghost的答案......
您的“第一种方式”不起作用有几个原因。
"http://adress1"
的命名空间。 .这是因为最外层元素具有默认命名空间声明 xmlns="http://adress1"
.所以这个默认命名空间被所有没有明确命名空间前缀的元素继承。因此,为了在 XPath 中选择这些元素,您必须告诉 XPath 您想要 namespace 中的元素,其 URI 为 "http://adress1"
。 . Ghost 展示了如何声明 namespace 前缀并在 XPath 中使用它。对于adress1
您可能使用的命名空间$attachment->registerXPathNamespace('ns1', 'http://adress1');
$attachment->xpath('contentDocument/...')
与输入文档的结构不匹配。 $attachment
保存输入文档的根节点,它是 <Document>
的不可见父节点.然后你试图选择一个名为 contentDocument
的根节点的子节点。 .但是<contentDocument>
是 <Document>
的 child ,而不是根节点。所以你需要像 $attachment->xpath('/*/ns1:contentDocument/ns1:Values/ns1:Attachments/*');
这样的东西关于PHP解析xml问题与获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24926255/