0

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.

habman
  • 1
  • `(string) $xml->attributes()->USER_ID` should work – Scuzzy Nov 08 '18 at 20:12
  • 3
    Possible duplicate of [Accessing @attribute from SimpleXML](https://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml) – Patrick Q Nov 08 '18 at 20:13
  • ```$user_id=(@DOMDocument::loadHTML($xml))->getElementsByTagName("status")->item(0)->getAttribute("USER_ID"); $text=(@DOMDocument::loadHTML($xml))->getElementsByTagName("status")->item(0)->textContent; var_dump($user_id,$text);``` – hanshenrik Nov 08 '18 at 22:10

2 Answers2

0

Try this one below

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

Hope this will help you.

Jesus Erwin Suarez
  • 1,571
  • 16
  • 17
0

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')."\n";
//get the contents of the tag as a string
echo "Status:" .$XMLReader->readString();

Output:

USER_ID:xxxxx
Status:OK

Sandbox

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38