2012-08-04 50 views
1

如何使用PHP我得到的屬性值秒:PHP和XML屬性跟進

<yt:duration seconds='12445'/> 

這是我迄今所做的:

 $xmlstr = file_get_contents($xml); 
    $xml_content = new SimpleXMLElement($xmlstr); 
    echo $xml_content->xpath('//yt:duration')->attributes; 
    print_r($xml_content->xpath('//yt:duration')); 
    echo $xml_content->xpath('//yt:duration')->attributes()->seconds; 

,顯示這些消息:

Notice: Trying to get property of non-object in C:\xampp\htdocs\ytm\xmlTest.php on line 22 
Array ([0] => SimpleXMLElement Object ([@attributes] => Array ([seconds] => 12445))) 
Notice: Trying to get property of non-object in C:\xampp\htdocs\ytm\xmlTest.php on line 24 

Notice: Trying to get property of non-object in C:\xampp\htdocs\ytm\xmlTest.php on line 24 

回答

2

此:

$xml_content->xpath('//yt:duration') 

返回一個數組(因爲你的print_r()會告訴你)。你必須以與對應於<yt:duration>節點的SimpleXMLElement工作搶到的第一個元素(位於索引0):

$list = $xml_content->xpath('//yt:duration'); 
$node = $list[0]; 

然後,你可以得到attibutes與attributes()

$attributes = $node->attributes(); 
echo $attributes['seconds']; // Not 100% sure on this, might be $attributes->seconds 
+0

這工作完美。謝謝 – rob 2012-08-04 20:16:52