Home » Php » PHP cURL, extract an XML response

PHP cURL, extract an XML response

Posted by: admin April 23, 2020 Leave a comment


I am invoking PHP cURL method on a server and the response is XML type. cURL is saving the output (after removing the tags) in a scalar type variable. Is there a way to store it in an object/hash/array so that it’s easy to parse?

How to&Answers:
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);          
    return $retValue;

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

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


Just add header('Content-type: application/xml'); before your echo of the XML response and you will see an XML page.



<song dateplayed="2011-07-24 19:40:26">
    <title>I left my heart on Europa</title>
    <artist>Ship of Nomads</artist>
<song dateplayed="2011-07-24 19:27:42">
    <title>Oh Ganymede</title>
<song dateplayed="2011-07-24 19:23:50">
    <artist>Jewitt K. Sheppard</artist>


$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;

Output on your browser: Ship of Nomads

credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5


no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it’s up to you what to do with it.

use JSON if possible (and json_decode) – it’s easier to work with, if not possible, use any XML library for parsin such as DOMXML:


$sXML = download_page('http://alanstorm.com/atom');
// Comment This    
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
//  echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);


simple load xml file ..

$xml = @simplexml_load_string($retValuet);

$status = (string)$xml->Status; 
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;