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()が言うように)。<yt:duration>ノードに対応する SimpleXMLElement を操作するには、最初の要素 (インデックス 0) を取得する必要があります。

$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 に答える