使用命名空间Simplexml读取节点

时间:2012-07-04 16:04:02

标签: php namespaces simplexml xml-namespaces

我有以下xml代码:

档案1.xml

<?xml version="1.0" encoding="utf-8"?>
 <DataSet xmlns="">
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
   <dsAanbod>
    <Pand diffgr:id="Pand1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
      <PandID>231384</PandID>
    </Pand>
   </dsAanbod>
 </diffgr:diffgram>
</DataSet>

我如何阅读

之间的数据

我有以下php代码

<?php 


    $xml_url = "1.xml";
    $xml = simplexml_load_file($xml_url);

    foreach ($xml as $entry){

       //Use that namespace
       $namespaces = $entry->getNameSpaces(true);
       //Now we don't have the URL hard-coded
       $diffgr = $entry->children($namespaces['diffgr']); 
       echo $diffgr->diffgram->dsAanbod->Pand->PandID;
}


?> 

但这不起作用。

有人可以帮助我访问它是名称空间元素子节点的节点。

亲切的问候

1 个答案:

答案 0 :(得分:2)

哦,从哪里开始。这个工作代码可能会说明一些问题:

<?php
    $xml_url = "1.xml";
    $xml = simplexml_load_file($xml_url);
    foreach($xml->children('diffgr',true) as $diffgr){
            $weirdemptynamespace = $diffgr->children('',true);
            echo $weirdemptynamespace->dsAanbod->Pand->PandID;
   }

列举一些问题:

  1. xmlns=""与没有命名空间不一样,在我看来,只是......好吧,很奇怪。
  2. 您的foreach为时过早(应在根元素(children('diffgr'))上调用Dataset
  3. 如果您只对名称空间前缀感兴趣,只需将children()的第二个参数设置为true
相关问题