1

I'm using an API to send a request to a webservice, and it returns me an XML, but I don't know how to read the XML values

Here is my code:

    $url = 'http://urlexample';

    $headers = array(
        "Content-type: application/x-www-form-urlencoded",
        "Accept: application/x-www-form-urlencoded"
    );

    $method = 'GET';

    $connection = new Varien_Http_Adapter_Curl();

    if ($method == "GET") {
        $zendMethod = Zend_Http_Client::GET;
    } elseif ($method == "POST") {
        $zendMethod = Zend_Http_Client::POST;
    } elseif ($method == "PUT") {
        $zendMethod = Zend_Http_Client::PUT;            
        $connection->addOption(CURLOPT_CUSTOMREQUEST, "PUT");
        $connection->addOption(CURLOPT_POSTFIELDS, $body);
    }

    $connection->setConfig(
        array(
        'timeout'   => 30
        )
    );

    $connection->write($zendMethod, $url, '1.0', $headers, $body);
    $response = $connection->read();
    $connection->close();

    $httpCode = Zend_Http_Response::extractCode($response);
    $response = Zend_Http_Response::extractBody($response);


    echo "<textarea>" . $response . "</textarea>" ;

The xml it returns:

<?xml version="1.0" encoding="utf-8"?>
<DataSet xmlns="http://">
<xs:schema id="NewDataSet" xmlns=""     xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
        <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="Produtos">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="TIMESTAMP" type="xs:dateTime" minOccurs="0" />
                            <xs:element name="DEPARTAMENTO" type="xs:string" minOccurs="0" />
                            <xs:element name="CATEGORIA" type="xs:string" minOccurs="0" />
                            <xs:element name="SUBCATEGORIA" type="xs:string" minOccurs="0" />
                            <xs:element name="FABRICANTE" type="xs:string" minOccurs="0" />
                            <xs:element name="CODIGO" type="xs:string" minOccurs="0" />
                            <xs:element name="DESCRICAO" type="xs:string" minOccurs="0" />
                            <xs:element name="DESCRTEC" type="xs:string" minOccurs="0" />
                            <xs:element name="PARTNUMBER" type="xs:string" minOccurs="0" />
                            <xs:element name="EAN" type="xs:string" minOccurs="0" />
                            <xs:element name="GARANTIA" type="xs:int" minOccurs="0" />
                            <xs:element name="PESOKG" type="xs:decimal" minOccurs="0" />
                            <xs:element name="PRECOREVENDA" type="xs:decimal" minOccurs="0" />
                            <xs:element name="PRECOSEMST" type="xs:decimal" minOccurs="0" />
                            <xs:element name="DATAVALIDADEPRECO" type="xs:dateTime" minOccurs="0" />
                            <xs:element name="DISPONIVEL" type="xs:int" minOccurs="0" />
                            <xs:element name="URLFOTOPRODUTO" type="xs:string" minOccurs="0" />
                            <xs:element name="ESTOQUE" type="xs:string" minOccurs="0" />
                            <xs:element name="NCM" type="xs:string" minOccurs="0" />
                            <xs:element name="LARGURA" type="xs:decimal" minOccurs="0" />
                            <xs:element name="ALTURA" type="xs:decimal" minOccurs="0" />
                            <xs:element name="PROFUNDIDADE" type="xs:decimal" minOccurs="0" />
                            <xs:element name="ATIVO" type="xs:int" minOccurs="0" />
                            <xs:element name="SUBSTTRIBUTARIA" type="xs:int" minOccurs="0" />
                            <xs:element name="ORIGEMPRODUTO" type="xs:string" minOccurs="0" />
                            <xs:element name="ESTOQUEDISPONIVEL" type="xs:decimal" 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="">
        <Produtos diffgr:id="Produtos1" msdata:rowOrder="0">
                <TIMESTAMP>2017-08-11T11:09:26-03:00</TIMESTAMP>
                <DEPARTAMENTO></DEPARTAMENTO>
                <CATEGORIA></CATEGORIA>
                <SUBCATEGORIA></SUBCATEGORIA>
                <FABRICANTE>GENIUS</FABRICANTE>
                <CODIGO>0064703</CODIGO>
                <DESCRICAO></DESCRICAO>
                <DESCRTEC></DESCRTEC>
                <PARTNUMBER>31731047103</PARTNUMBER>
                <EAN>4710268244738</EAN>
                <GARANTIA>12</GARANTIA>
                <PESOKG>3.1000</PESOKG>
                <PRECOREVENDA>95.0000</PRECOREVENDA>
                <PRECOSEMST>95.0000</PRECOSEMST>
                <DATAVALIDADEPRECO></DATAVALIDADEPRECO>
                <DISPONIVEL>1</DISPONIVEL>
                <URLFOTOPRODUTO></URLFOTOPRODUTO>
                <ESTOQUE>RJ</ESTOQUE>
                <NCM></NCM>
                <LARGURA>0.3000</LARGURA>
                <ALTURA>0.3500</ALTURA>
                <PROFUNDIDADE>0.1700</PROFUNDIDADE>
                <ATIVO>1</ATIVO>
                <SUBSTTRIBUTARIA>0</SUBSTTRIBUTARIA>
                <ORIGEMPRODUTO></ORIGEMPRODUTO>
                <ESTOQUEDISPONIVEL>63.0000</ESTOQUEDISPONIVEL>
            </Produtos>
            <Produtos diffgr:id="Produtos2" msdata:rowOrder="1">
                <TIMESTAMP>2017-08-14T18:01:00-03:00</TIMESTAMP>
                <DEPARTAMENTO></DEPARTAMENTO>
                <CATEGORIA></CATEGORIA>
                <SUBCATEGORIA></SUBCATEGORIA>
                <FABRICANTE>GENIUS</FABRICANTE>
                <CODIGO>0064694</CODIGO>
                <DESCRICAO></DESCRICAO>
                <DESCRTEC></DESCRTEC>
                <PARTNUMBER>31731006100</PARTNUMBER>
                <EAN>4710268238461</EAN>
                <GARANTIA>12</GARANTIA>
                <PESOKG>0.4900</PESOKG>
                <PRECOREVENDA>28.9900</PRECOREVENDA>
                <PRECOSEMST>28.9900</PRECOSEMST>
                <DATAVALIDADEPRECO></DATAVALIDADEPRECO>
                <DISPONIVEL>1</DISPONIVEL>
                <URLFOTOPRODUTO></URLFOTOPRODUTO>
                <ESTOQUE>RJ</ESTOQUE>
                <NCM>85182100            </NCM>
                <LARGURA>0.1500</LARGURA>
                <ALTURA>0.1200</ALTURA>
                <PROFUNDIDADE>0.0700</PROFUNDIDADE>
                <ATIVO>1</ATIVO>
                <SUBSTTRIBUTARIA>0</SUBSTTRIBUTARIA>
                <ORIGEMPRODUTO></ORIGEMPRODUTO>
                <ESTOQUEDISPONIVEL>100.0000</ESTOQUEDISPONIVEL>
            </Produtos>
        </NewDataSet>
    </diffgr:diffgram>
</DataSet>

The echo in the last was just so I could see the xml, it works but I don't know how to read it. It shows a list of products and attributes. I have tried with SimpleXML but I wasn't successful

Edit: Just realized I should have posted it in PHP session instead of Magento hehehe sorry

1
  • Shouldn't this non-Magento-specific question be on Stack Overflow instead?
    – dotancohen
    Jul 10, 2022 at 13:30

4 Answers 4

1

You could try using SimpleXMLElements instead.
Just initiate it with $xml = new \SimpleXMLElement($response); and dump that.

1

You can use simplexml_load_string which will interpret a string of XML into an object.

Example

$response="<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

$xml= simplexml_load_string($response);

You can also convert your Object to array by combining json_encode and json_decode

$xml=simplexml_load_string($response);
print_r(json_decode(json_encode($xml), true)); // Will return you array
3
  • That returns a blank array, "Array ( )". Shouldn't I be able to see the values?
    – Stordon
    Aug 18, 2017 at 13:31
  • The above example gives me the result. You can paste your xml response.
    – Priyank
    Aug 18, 2017 at 13:39
  • @Priyank My soap return as Object, how can i return as XML?
    – zus
    Nov 15, 2018 at 8:58
1

if I understand you right, you want to read the values of your xml response. Here is a full documentation (http://php.net/manual/en/class.simplexmlelement.php);

And then you can use it as object.

For example you have this response:

$response = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

You need to make this:

$xml = simplexml_load_string($response);

And then if you need value of <title> write this code: $title = $xml->title;.

If your xml response looks like this:

<config>
    <data>
        <value1>somevalue</value1>
        <value2>somevalue</value2>
        <value3>somevalue</value3>
        <value4>somevalue</value4>
   </data>
</config>

And you need to get value of <value1>, just make this construction $value1 = $xml->data->value1;.

If something isn't clear, ask me in comments to my answer

7
  • Hi! Thank you for your reply! I add this to end of code $response = simplexml_load_string($response); print_r($response); and it shows object(SimpleXMLElement)#22 (0) { }, is it correct? Or should return something else
    – Stordon
    Aug 18, 2017 at 13:26
  • @Stordon , yes. If you want to look on it as on object use var_dump($response); Aug 18, 2017 at 13:27
  • using var_dump it shows me a blank page. I'm gonna edit my post with the XML it returns
    – Stordon
    Aug 18, 2017 at 13:33
  • Maybe your server blocks var_dump, try to var_dump('test'); and say what you see Aug 18, 2017 at 13:35
  • It shows string(4) "test". I edited my post with my xml
    – Stordon
    Aug 18, 2017 at 14:01
0

I suggest the following method which magento 2.4 used inside its core modules.

 $xml = new \Magento\Framework\Simplexml\Config();
        $xml->loadString($xmlResponse);
        $arr = $xml->getXpath("//DataSet/NewDataSet/Produtos/text()");
1
  • If you convert this code example to DI then I'll happily upvote it.
    – dotancohen
    Jul 10, 2022 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.