如何使用php获取秒的属性值:
<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
答案 0 :(得分:2)
此:
$xml_content->xpath('//yt:duration')
返回一个数组(正如您的print_r()
会告诉你的那样)。您必须获取第一个元素(在索引0处)才能使用与<yt:duration>
节点对应的SimpleXMLElement:
$list = $xml_content->xpath('//yt:duration');
$node = $list[0];
然后,您可以使用attributes()
:
$attributes = $node->attributes();
echo $attributes['seconds']; // Not 100% sure on this, might be $attributes->seconds