Akaash K
Akaash K

Reputation: 11

Fetch xml data from API response

Request:

$headers = array(   'Content-Type:application/xml'  ); 
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => 'https://example.com',
            CURLOPT_POST => 1,
            CURLOPT_HEADER => $headers,
            CURLOPT_USERPWD=>'test:test',
            CURLOPT_POSTFIELDS => $XMLData
        ));
        $APIResponse = curl_exec($curl);
        curl_close($curl);

And I get this response from an API

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: ----
X-AspNet-Version: -----
X-Powered-By: ASP.NET
Date: ---- GMT
Content-Length: 100

<?xml version="1.0" encoding="utf-8"?><response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.example.com"><ID>12345</ID></response>

I want to fetch ID from xml ID tag. How can I get that in my php code?

Upvotes: 1

Views: 224

Answers (1)

ADyson
ADyson

Reputation: 62059

You're getting the HTTP header data included within your response from cURL, which is making it hard to extract the XML part.

However this is happening due to a simple misunderstanding - the CURLOPT_HEADER option doesn't do what you think it does.

That doesn't include your request headers in the request (as your code seems to be trying to do), instead it sets an option telling cURL whether or not the response headers should be included in the main output or not. If you set

CURLOPT_HEADER => 0 

in your code, your problem should go away - then only the response body (in your case, just the XML) will included in the output from curl_exec.

In the meantime, if you need to set custom HTTP headers in your request, you can do it via the CURLOPT_HTTPHEADER option - a detailed example can be found here and in many other places online.

P.S. Admittedly these option names are not, in themselves, very clear about the difference between them, but the PHP manual does describe what they do in more detail.

Upvotes: 1

Related Questions