Home > Enterprise >  Echo specific value of a key of an array generated from an XML
Echo specific value of a key of an array generated from an XML

Time:09-28

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.

CodePudding user response:

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

  • Related