When I use simplexml_load_file from a webservice, it returns
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.cebroker.com/CEBrokerWebService/"><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/19/2022
4:53:35 AM" /></licensees></string>
But, I cannot parse it as XML to get the attributes. I need it to be formatted as such:
<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 then this code works:
$xml_string = simplexml_load_string($xmlresponse);
foreach ($xml_string->licensee[0]->attributes() as $a => $b) {
echo $a , '=' , $b;
}
I tried str_replace and decoding, without success.
The contents of the "string" element is an XML document itself - stored in an text node. You can consider it an envelope. So you have to load the outer XML document first and read the text content, then load it as an XML document again.
$outerXML = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.cebroker.com/CEBrokerWebService/"><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/19/2022
4:53:35 AM" /></licensees></string>
XML;
$envelope = new SimpleXMLElement($outerXML);
$licensees = new SimpleXMLElement((string)$envelope);
echo $licensees->asXML();
In DOM:
$envelope = new DOMDocument();
$envelope->loadXML($outerXML);
$document = new DOMDocument();
$document->loadXML($envelope->documentElement->textContent);
echo $document->saveXML();
Since the XML you want seem to be stored as htmlentities, your first simplexml_load_string() won't read it as XML. If you take that string and run that through simplexml_load_string() as well then you'll get it as XML:
$xml_string = simplexml_load_string($xmlresponse);
$licensees = simplexml_load_string($xml_string);
var_dump($licensees);
Output:
object(SimpleXMLElement)#2 (1) {
["licensee"]=>
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(10) {
["valid"]=>
string(4) "true"
["State"]=>
string(2) "FL"
["licensee_profession"]=>
string(2) "RN"
["licensee_number"]=>
string(7) "2676612"
["state_license_format"]=>
string(0) ""
["first_name"]=>
string(5) "HENRY"
["last_name"]=>
string(6) "GEITER"
["ErrorCode"]=>
string(0) ""
["Message"]=>
string(0) ""
["TimeStamp"]=>
string(21) "2/19/2022 4:53:35 AM"
}
}
}
Here's a demo: https://3v4l.org/da3Up
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With