使用PHP解析非常简单的XML

Very simple request (I think) that I have had no luck with.

Here is the contents of the xml file:

<?xml version="1.0" encoding="utf-8"?>
<status USER_ID="xxxxx">OK</status>

Current php:

$xml=simplexml_load_file($file) or die("Error: Cannot create object");
print_r($xml);

Outputs:

SimpleXMLElement Object ( [@attributes] => Array ( [USER_ID] => xxxxx ) [0] => OK ) 

And now I'm stuck

How can I get the value of USER_ID and that the status was "OK" into my php script.

Thanks.

Try this one below

echo "Display the user id: " . $xml['USER_ID'];
echo "Display the status: " . $xml[0];

Hope this will help you.

If you don't like SimpleXml (like me), you can also use the XMLReader Class like:

$XMLReader = new XMLReader;
$XMLReader->XML(file_get_contents($file)); //you can use $XMLReader->open('file://'.$file); too
//move to first node
$XMLReader->read();
//get an attribute
echo "USER_ID:".$XMLReader->getAttribute('USER_ID')."
";
//get the contents of the tag as a string
echo "Status:" .$XMLReader->readString();

Output:

USER_ID:xxxxx
Status:OK

Sandbox