SimpleXML - Cannot get attributes of first tag

时间秒杀一切 提交于 2019-12-10 10:05:20

问题


I am trying to read the attributes of the first tag of an XML. Here's the XML structure

<myxml timestamp="1301467801">
    <tag1>value1</tag1>
    <tag2>value2</tag2>
    …
</myxml>

And here's how I try to get the timestamp attribute (tried 2 approaches, listing them both here, none works)

$timestamp = $xml->myxml->attributes()->timestamp; //gives Node no longer exists warning
if($xml->myxml && $xml->myxml->attributes()){ //Doesn't enter this loop
    $arr = $xml->myxml->attributes();
    $timestamp = $arr['timestamp'];
}

Can someone please let me know how I can get the attribute's value? Thanks.


回答1:


It's because your $xml actually points to the root element. Correct usage would be:

$timestamp = $xml->attributes()->timestamp;




回答2:


The right way to access attributes [as long as they belong to the node's namespace] is to use the array notation. Reserve attributes for namespaced attributes.

Also, you should name the variable that represent your XML document after its root node. It's a good practice that prevents many mixups.

$myxml = simplexml_load_string(
    '<myxml timestamp="1301467801">
        <tag1>value1</tag1>
        <tag2>value2</tag2>
    </myxml>'
);

echo $myxml['timestamp'];



回答3:


<?php
$myxml = simplexml_load_string(
        '<myxml timestamp="1301467801">
        <tag1>value1</tag1>
        <tag2>value2</tag2>
    </myxml>'
);

$test = $myxml['timestamp'];
// will asign simpleXMLElement
echo $test; // -> will print nothing

// you need to cast the simpleXMLElement attribute as STRING!!! 
$test = (string)$myxml['timestamp'];
echo $test;
?>


来源:https://stackoverflow.com/questions/5483877/simplexml-cannot-get-attributes-of-first-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!