Reputation: 1204
Recently i had to do an api call which returned an XML response. But it seems like a strange XML with only 1 base tag and all other info is given as string inside this base tag. I need to get the value of each of these string tags, But don't know how to achieve this.
Below given is the sample response am receiving from the api.
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://webservices/api/v1/Inventory.asmx">
<NewDataSet>
<Table>
<ITEMNO>120</ITEMNO>
<IDESC>BERG 22423 BULL .224 90GR VLD TGT 100</IDESC>
<IMFSEQ>570</IMFSEQ>
<IMFGNO>628</IMFGNO>
<CSEQ>0</CSEQ>
<ITYPE>7</ITYPE>
<SHDESC>Berger Bullets 22423 Target 22 Caliber .224 90 GR Target Very Low Drag 100 Box </SHDESC>
<UOM>EA</UOM>
<PRC1>34.73</PRC1>
<CPRC>34.04</CPRC>
<QTYOH>26</QTYOH>
<WTPBX>1.400</WTPBX>
<ITUPC>679459224239 </ITUPC>
<MFGINO>22423 </MFGINO>
<SCNAM1>BERG </SCNAM1>
<SCNAM2>B22CAL </SCNAM2>
<CATCD xml:space="preserve"> </CATCD>
<MFPRTYP xml:space="preserve"> </MFPRTYP>
<MFPRC>0.00</MFPRC>
<CATID>36</CATID>
<TXTREF>120</TXTREF>
<PICREF>120</PICREF>
<ITBRDNO>628</ITBRDNO>
<SERIES>Match Grade </SERIES>
<LENGTH>4.1</LENGTH>
<HEIGHT>1.2</HEIGHT>
<WIDTH>3.3</WIDTH>
<HAZAIR xml:space="preserve"> </HAZAIR>
<HAZGRND xml:space="preserve"> </HAZGRND>
<CHGDTE>2018-05-23T00:00:00+00:00</CHGDTE>
<LOADDT>2015-11-05T00:00:00+00:00</LOADDT>
</Table>
</NewDataSet>
</string>
I tried the below methods but it does not seems to work as needed
<?php
$xml=simplexml_load_string($myXMLData);
print_r($xml);
$xml = new SimpleXMLElement($myXMLData);
print_r($xml);
?>
what am looking is to get the value of each of the tags inside the response. Any help is much appreciated.
Upvotes: 1
Views: 201
Reputation: 19512
You have an XML document as text inside another XML document. So you have to load the outer document, fetch the text content and parse it as XML again:
$xml = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://webservices/api/v1/Inventory.asmx">
<NewDataSet>
<Table>
<ITEMNO>120</ITEMNO>
<IDESC>BERG 22423 BULL .224 90GR VLD TGT 100</IDESC>
</Table>
</NewDataSet>
</string>
XML;
$stringElement = new SimpleXMLELement($xml);
echo $stringElement, "\n";
// force to string and parse as XML
$newDataSet = new SimpleXMLElement((string)$stringElement);
echo $newDataSet->Table->ITEMNO;
Output:
<NewDataSet>
<Table>
<ITEMNO>120</ITEMNO>
<IDESC>BERG 22423 BULL .224 90GR VLD TGT 100</IDESC>
</Table>
</NewDataSet>
120
Upvotes: 1
Reputation: 14927
You could make use of html_entity_decode
to transform your string into proper XML:
$xml = new SimpleXMLElement(html_entity_decode($myXMLData));
print_r($xml);
Demo here: https://3v4l.org/AWWEH
Upvotes: 1