1

如何使用 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
4

1 回答 1

2

这:

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

返回一个数组(正如您print_r()将告诉您的那样)。您必须获取第一个元素(在索引 0 处)才能使用与节点对应的 SimpleXMLElement <yt:duration>

$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
于 2012-08-04T19:51:41.647 回答