无法使用PHP获取XML属性值

时间:2013-01-25 08:46:49

标签: php xml xml-parsing nodes xmlnode

<Pages TotalPages="56" ProductCode="Headline" PubDate="2012-01-31" PubVersion="0" PubSubVersion="0" PageWidth="1622" PageHeight="1902">
              <Page PageNo="1" PageName="" PageType="" Section="Section" ThumbnailPath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/1/Pv001.png" ImagePath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/1/Pg001_142_p.jpg" OverlayFullPath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/1/Pg001_142_t.png" PreviewPath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/1/Pg001.png" IsPreview="true" ImageHeight="1902" ImageWidth="1622" WithResource="true" /> 
              <Page PageNo="2" PageName="" PageType="" Section="Section" ThumbnailPath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/2/Pv002.png" ImagePath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/2/Pg002_142_p.jpg" OverlayFullPath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/2/Pg002_142_t.png" PreviewPath="http://203.80.1.28/FlippingBook/Dev/Frontend/demo/Headline/2012/12/20/0/0/A/Content/2/Pg002.png" IsPreview="true" ImageHeight="1902" ImageWidth="1622" WithResource="true" /> 
</Pages>

PHP:

$xml = simplexml_load_file($dir) 
       or die("Error: Cannot create object");
//$fileList = array();

foreach($xml->children() as $Pages){
    foreach($Pages->children() as $Page => $page){
    $fileLink = $page['ThumbnailPath'];
    echo $fileLink;
    }
}

我将得到的是来自节点“页面”的ThumbnailPath,我循环浏览页面和页面,但事实证明什么都没有,如何解决这个问题?感谢

3 个答案:

答案 0 :(得分:1)

很容易修复

$xml = simplexml_load_file("test.xml")
       or die("Error: Cannot create object");
//$fileList = array();


foreach($xml->children() as $Pages){
    print_r($Pages['ThumbnailPath']);
}

答案 1 :(得分:1)

您不必遍历“Pages”,因为它已经是xml根元素。所以你可以省略第二个循环:

 $xml = simplexml_load_string($string) or die("Error: Cannot create object");
 //$fileList = array();

foreach($xml->children() as $Page){
    $fileLink = $Page['ThumbnailPath'];
    echo $fileLink;
}

答案 2 :(得分:1)

试试这个:

foreach($xml->children() as $Pages){
    echo $Pages['ThumbnailPath'][0].'<br>';
}