2013-01-31 86 views
2

我有以下的PHP和XML:PHP,XPath和SimpleXML的 - 的XPath不工作

$XML = <<<XML 
<items> 
    <item id="12"> 
     <name>Item A</name> 
    </item> 
    <item id="34"> 
     <name>Item B</name> 
    </item> 
    <item id="56"> 
     <name>Item C</name> 
    </item> 
</items> 
XML; 


$simpleXmlEle = new SimpleXMLElement($XML); 

print_r($simpleXmlEle->xpath('./item[1]')); 
print "- - - - - - -\n"; 
print_r($simpleXmlEle->xpath('./item[2][@id]')); 
print "- - - - - - -\n"; 
print_r($simpleXmlEle->xpath('./item[1]/name')); 

我能夠訪問ID這樣

$simpleXmlEle->items->item[0]['id'] 

由於它是一個動態的應用xpath在運行時以字符串形式提供,所以我相信我應該使用xpath。

上面PHP生產:

PHP:

Array 
(
    [0] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [id] => 12 
       ) 

      [name] => Item A 
     ) 

) 
- - - - - - - 
Array 
(
    [0] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [id] => 34 
       ) 

      [name] => Item B 
     ) 

) 
- - - - - - - 
Array 
(
    [0] => SimpleXMLElement Object 
     (
     ) 

) 

我理解的第一輸出,但第2個輸出內部的整體元件被返回,而不是僅僅的屬性。
1)有什麼想法爲什麼?

而且最後一個項目是空
2)這是爲什麼,什麼是正確的XPath?

我的目標是第二個和第三個輸出爲:34(第二元素的id屬性的值)項目A(只是第一個元素的名稱)。

回答

2

見下:

// name only 
$name = $simpleXmlEle->xpath("./item[1]/name"); 
echo $name[0], PHP_EOL; 

// id only 
$id = $simpleXmlEle->xpath("./item[2]/@id"); 
echo $id[0], PHP_EOL; 

打印:

Array ([0] => SimpleXMLElement Object ([0] => Item A)) 
Array ([0] => SimpleXMLElement Object ([@attributes] => Array ([id] => 34))) 

確保您請勿做:

print_r($objSimpleXML->xpath("//item[1]/name")); 

據//返回與所有元素的文檔這個名字,所以如果有更深層次上的item元素,那麼它的VA lue也被返回,這是不希望的。

希望幫助

+0

嘗試這樣做,它的作品,感謝 –

+0

以及@DamienPyseek話,不要忘了接受的答案 – Alex

+0

已經做到了現在的感謝 –