Home > Software design >  How to get data on an XML response from a PHP Guzzle requests
How to get data on an XML response from a PHP Guzzle requests

Time:10-29

I have the following request and am using guzzle to process it. I am attempting to get the ID and NAME hopefully in key => value array but it doesn't seem to work.

$api_url = 'http://example.com/test.asmx/GetUserDetails?userID=123';
$client = new Client();
$results = $client->request('GET', $api_url)->getBody()->getContents();
dd($results);

The response gotten when I echo $results is shown below

123EXAMPLE

Also, the response gotten when I dd($results) comes in triple quotes """ """ as shown below

"""
<?xml version="1.0" encoding="utf-8"?>

<DataSet xmlns="http://example.com">

  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Table">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="ID" type="xs:string" minOccurs="0" />
                <xs:element name="NAME" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <NewDataSet xmlns="">
      <Table diffgr:id="Table1" msdata:rowOrder="0">
        <ID>123</ID>
        <NAME>EXAMPLE</NAME>
      </Table>
    </NewDataSet>
  </diffgr:diffgram>
</DataSet>
"""

I tried using SimpleXMLElement but it resulted in this response SimpleXMLElement {#642}

$response1 = simplexml_load_string($results);
$response2 = SimpleXMLElement($results);

Also, I used json_encode and json_decode but none worked.

Please, any help is appreciated.

CodePudding user response:

It seems the namespaces are complicating the situation. This code:

$response2 = new SimpleXMLElement($results);
$children = $response2->children('diffgr', true);
$children2 = $children->children();
echo $children2->NewDataSet->Table->ID;
echo PHP_EOL; //newline
echo $children2->NewDataSet->Table->NAME;

will get you the data.

It first gets all the children of the outer XML which have the "diffgr" namespace (which is only one, in this case). Then within that child, its own child elements don't have a namespace again, so we have to use the children() function again without a namepsace specified in order to retrieve those.

Live demo: http://sandbox.onlinephpfunctions.com/code/3cd49767e5b1dd237d26b9f03ceff4dae0546eae

Credit to this post for the idea.

  • Related