SimpleXML - Cannot get attributes of first tag

为君一笑 提交于 2019-12-05 20:08:49

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