Skip to content
Advertisement

convert string to xml in PHP

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/">&lt;licensees&gt;&lt;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" /&gt;&lt;/licensees&gt;</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.

Advertisement

Answer

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/">&lt;licensees&gt;&lt;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" /&gt;&lt;/licensees&gt;</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();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement