Home > OS >  Get attributes from a returned XML string
Get attributes from a returned XML string

Time:02-19

I am trying to take an XML string returned from a call to CEBroker WebServices such as:

<licensees>
    <licensee valid="true" State="FL" licensee_profession="RN" 
        licensee_number="2676612" state_license_format="" first_name="HENRY" last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/18/2022 6:43:20 PM" />
</licensees>

And parse the string to obtain the values of the attributes as they will always be the same, and there will be only one licensee per string. The XML string is returned in $xmlresponse, and when I print it out using print_r it is correct, but when I try to parse, I always get nothing.

I tried

$xml_string = simplexml_load_string($xmlresponse);
print_r ("this is my xml after going through simplexml_load_string" . $xml_string);

//The above line prints nothing for $xml_string;

$json = json_encode($xml_string);
            print_r($json);
            $array = json_decode($json,TRUE);
            echo "<p>Array contents are as follows</p>";
            print_r($array);
            var_dump ($array);
            echo "<p>Array contents ended!</p>";

I am new to XML and just need to know how to parse nodes and, in this case attributes, for returned XML data or XML files.

Thanks

CodePudding user response:

If I understand your question correctly, try the following, which assumes a response with two licensees:

$xmlresponse = '
<licensees>
   <licensee valid="true" State="FL" licensee_profession="RN" licensee_number="2676612" state_license_format="" first_name="HENRY" last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/18/2022 6:43:20 PM" />
   <licensee valid="false" State="NY" licensee_profession="DC" licensee_number="1234" state_license_format="" first_name="JOHN" last_name="DOE" ErrorCode="" Message="" TimeStamp="1/1/2023 6:43:20 PM" />
</licensees>
';
$xml_string = simplexml_load_string($xmlresponse);
$licensees = $xml_string->xpath("//licensee");

foreach ($licensees as $licensee) {
    foreach ($licensee ->xpath('./@*') as $attribute){
    echo $attribute." ";
    }
    echo "\n";
}

Output:

true FL RN 2676612  HENRY GEITER   2/18/2022 6:43:20 PM 
false NY DC 1234  JOHN DOE   1/1/2023 6:43:20 PM 

Output

  • Related