Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Echo specific value of a key of an array generated from an XML

I have the following code:

$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
    <RESPONSE
        xmlns='http://www.ibm.com/maximo'
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' creationDateTime='2022-09-22T09:51:01+02:00' transLanguage='EN' baseLanguage='EN' messageID='993921663833062257153' maximoVersion='7 6 20180718-1141 V7610-83' rsStart='0' rsTotal='1' rsCount='1'>
        <CHANGE>
            <TEST>
                <CHANGEBY>TESTUSER</CHANGEBY>
                <CHANGEDATE>2022-09-21T17:42:21+01:00</CHANGEDATE>
                <CIA_DONE>YES</CIA_DONE>
            </TEST>
        </CHANGE>
    </RESPONSE>
</note>";

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
$array = json_decode(json_encode((array)$xml), TRUE);
print_r($array);

That returns the following result:

Array ( [RESPONSE] => Array ( [@attributes] => Array ( [creationDateTime] => 2022-09-22T09:51:01+02:00 [transLanguage] => EN [baseLanguage] => EN [messageID] => 993921663833062257153 [maximoVersion] => 7 6 20180718-1141 V7610-83 [rsStart] => 0 [rsTotal] => 1 [rsCount] => 1 ) [CHANGE] => Array ( [TEST] => Array ( [CHANGEBY] => TESTUSER [CHANGEDATE] => 2022-09-21T17:42:21+01:00 [CIA_DONE] => YES ) ) ) )

Now I want to echo the value of "CHANGEDATE", but echo $array["note"]["RESPONSE"]["CHANGE"]["TEST"]["CHANGEBY"]; returns nothing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s no need to go to JSON, you can use your SimpleXML object directly:

echo $xml->RESPONSE->CHANGE->TEST->CHANGEBY;

However, if you really want/need to, the root element note needs to be skipped:

echo $array["RESPONSE"]["CHANGE"]["TEST"]["CHANGEBY"];

Demo: https://3v4l.org/fbTpB

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading