PHP Curl, Extract an Xml Response

PHP cURL, extract an XML response


<?php
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
echo $oEntry->title . "\n";
}

returning a XML response with CURL

Your code retrieve full XML, to see it write:

echo htmlentities( $server_output );
die();

and in the browser you'll see:

<?xml version="1.0" encoding="utf-16" ?>
<ChameleonIAPIResponse>

<Titles><TitleId>1</TitleId><Title></Title><TitleId>6</TitleId><Title>Mr</Title><TitleId>2</TitleId><Title>Mrs</Title><TitleId>3</TitleId><Title>Miss</Title><TitleId>4</TitleId><Title>Ms</Title><TitleId>5</TitleId><Title>Dr</Title><TitleId>43</TitleId><Title>Sir</Title></Titles>
</ChameleonIAPIResponse>

The problem is that the browser interpret your output as HTML, so the tag are hidden (see at the browser page source, and you will find your complete XML).

In addition, to send XML as XML, before you have to send appropriate headers:

header( 'Content-type: text/xml' );
echo $server_output;
die();

No other output before and after above code, otherwise your XML will result broken.

If you prefer SimpleXML, you can do this:

$oXML = new SimpleXMLElement( $server_output );
header( 'Content-type: text/xml' );
echo $oXML->asXML();
die();

Also in this case, no output before and after (So comment previous lines).

how to parse xml response and assign to a variable using CURL in php

A possible solution could be to add the CURLOPT_RETURNTRANSFER option:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

From the manual:

TRUE to return the transfer as a string of the return value of
curl_exec() instead of outputting it out directly.

You can use for example simplexml_load_string to load the returned string and access its properties:

<?php
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://x.x.x.x:/ussd/process? destination=BANGLA&userName=&secondarySource=01");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$retValue = curl_exec($ch);

$simpleXMLElement = simplexml_load_string($retValue);
$description = (string)$simpleXMLElement->response->description;
$username = (string)$simpleXMLElement->transaction->userName;
// etc ..

Parse CURL XML response PHP

You can try this

$string = '<result>
<contact id="90676">
<Group_Tag name="Sequences and Tags">
<field name="Contact Tags (Raw)">
test test
</field>
</Group_Tag>
</contact>
</result>';

$xml = simplexml_load_string($string);

if($xml->contact->Group_Tag['name'] == 'Sequences and Tags'){
if($xml->contact->Group_Tag->field['name'] == 'Contact Tags (Raw)'){
echo $xml->contact->Group_Tag->field;
}
}

Updated

<?php
$xml=simplexml_load_file("http://i.shn-host.ru/json/srch.php") or die("Error: Cannot create object");

foreach ($xml->contact->Group_Tag as $Group_Tag) {
if($Group_Tag['name'] == 'Sequences and Tags'){
foreach ($Group_Tag as $field) {
if($field['name'] == 'Contact Tags (Raw)'){
echo $field;
}
}
}
}
?>

Result I got

22*/96/72/77/78/79/82/105/121/136/146/209/246/259/260/262/264/281/*282

cURL to get XML response from an API not working

Rather than trying to send the url parameters within the headers ( as noted by @CBroe earlier ) you need to create the url with querystring before calling curl_init

$url = "https://ws.fr.shopping.rakuten.com/stock_ws";
$headers = array(
"Accept: application/xml"
);
$args=array(
"action"=>"export",
"login"=>"mylogin",
"pwd"=>"mytokenxxx",
"version"=>"2018-06-29"
);
$url=sprintf('%s?%s',$url,http_build_query( $args ));

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);

var_dump($resp);

Which then unsurprisingly yields:

string(584) " Sender InvalidUserConnection Unknown user or password.
Details

Get body content from xml in php curl request

SimpleXML is an object. It isn't the full XML string as you might think. Try this.

//Cast to string to force simpleXml to convert into a string
$xmlString = $xml->asXML();
echo $xmlString . "\n";

I'm pretty sure you can't do this because $response is XML. Trying to json_encode it doesn't make sense.

$json = json_encode($response);

I did this:

<?php
$x = '<?xml version="1.0" ?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>...</env:Header>
<env:Body>
<GetStatusResponse xmlns:s1="http://Xyz.Abc" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://tempuri.org/" xmlns="http://tempuri.org/">
<s1:StatusResponse>
<s1:Test ResponseCode="INPROGRESS" ResponseMessage="Reference no. 12345"/>
</s1:StatusResponse>
</GetStatusResponse>
</env:Body>
</env:Envelope>';
$xml = simplexml_load_string($x);
echo $xml->asXml();
echo "\n";

And I get this output:

<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>...</env:Header>
<env:Body>
<GetStatusResponse xmlns:s1="http://Xyz.Abc" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://tempuri.org/" xmlns="http://tempuri.org/">
<s1:StatusResponse>
<s1:Test ResponseCode="INPROGRESS" ResponseMessage="Reference no. 12345"/>
</s1:StatusResponse>
</GetStatusResponse>
</env:Body>
</env:Envelope>

This explains how to specify namespaces.
https://www.php.net/manual/en/simplexmlelement.attributes.php

$xml->registerXPathNamespace('e', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('s', 'http://Xyz.Abc');
$result = $xml->xpath('//s:Test');
$response = $result[0]->attributes();
echo "Response Code = " . $response['ResponseCode'] . "\n";
echo "Response Message = " . $response['ResponseMessage'] . "\n";

Read xml data from url using curl and php

Here is some sample code (XML parsing module may not be available on your PHP installation):

<?php

$url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents

$data = curl_exec($ch); // execute curl request
curl_close($ch);

$xml = simplexml_load_string($data);
print_r($xml);

?>

The variable $xml now is a multi-dimensional key value array and you should easily be able to figure out how to get the elements from there.

PHP - Curl - Soap Response (Get data from xml tags)

Using SimpleXML you can read the code and the data much easier. The only thing is that you need to respect the namespaces. So first register the ns2 namespace so that you can then you can fetch the <ns2:accountMovement> elements. The loop over these, but to access the child elements in the namespace, use children("http://www.mygemini.com/schemas/mygemini") to get them into the $data variable, then each access is via this (i.e. $data->paymentId)...

$xml = simplexml_load_string($xmlContent);
$xml->registerXPathNamespace("ns2", "http://www.mygemini.com/schemas/mygemini");
$movements = $xml->xpath("//ns2:GetAccountMovementsResponseIo/ns2:accountMovement");
foreach ( $movements as $accMove ) {
$data = $accMove->children("http://www.mygemini.com/schemas/mygemini");
echo "paymentId ->".$data->paymentId.PHP_EOL;
echo "externalPaymentId ->".$data->externalPaymentId.PHP_EOL;
echo "debitCredit ->".$data->debitCredit.PHP_EOL;
}

PHP Curl and XML Response - Updated

the result is a string not a file.
try using simplexml_load_string instead of simplexml_load_file.

$Products = simplexml_load_string($response);


Related Topics



Leave a reply



Submit