PHP解析xml的get值问题


PHP parsing xml issues with get values

我收到的文件是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都返回空对象。

我不知道是什么问题。你能帮我找到每一个数据附件吗?

谢谢你的帮助。

详细说明@Ghost的回答…

你的"第一种方式"行不通有几个原因。

  1. 输入XML中的大多数元素都在默认名称空间中,该名称空间的URI为"http://adress1"。这是因为最外层的元素具有默认的名称空间声明xmlns="http://adress1"。因此,所有没有显式名称空间前缀的元素都会继承这个默认名称空间。因此,为了在XPath中选择这些元素,必须告诉XPath希望在URI为"http://adress1"的名称空间中选择元素。Ghost展示了如何声明名称空间前缀并在XPath中使用它。对于adress1命名空间,您可以使用$attachment->registerXPathNamespace('ns1', 'http://adress1');

  2. 其次,$attachment->xpath('contentDocument/...')与输入文档的结构不匹配。$attachment保存输入文档的根节点,它是<Document>的不可见父节点。然后尝试选择名为contentDocument的根节点的子节点。但是<contentDocument><Document>的子节点,而不是根节点。所以你需要输入$attachment->xpath('/*/ns1:contentDocument/ns1:Values/ns1:Attachments/*');

如果选择使用xpath,则需要先注册名称空间。使用registerXPathNamespace

的例子:

$attachToDecode = array();
$attachment = new SimpleXMLElement(file_get_contents($file1));
$attachment->registerXPathNamespace('str', 'adress6');
foreach($attachment->xpath('//str:DataAttachment') as $strAttachment) {
    $attachToDecode[] = (string) $strAttachment;
}
echo '<pre>';
print_r($attachToDecode);
样本输出:

VALUESRECEIVE
VALUESToRECEIVE
VALUESToRECEIVE