开发者

SimpleXML - Cannot get attributes of first tag

I am tryin开发者_如何学运维g 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.


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

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


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'];


<?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;
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜