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?
Asked
Active
Viewed 1.5e+01k times
38
-
Could you expand on what you mean by "after removing the tags". – Alana Storm Feb 18 '09 at 23:01
6 Answers
117
<?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";
}

Alana Storm
- 164,128
- 91
- 395
- 599
-
How do we read 
Jason Plank
- 2,336
- 5
- 31
- 40

arkleyjoe
- 131
- 2
- 3
5
Example:
<songs>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
<title>Kallichore</title>
<artist>Jewitt K. Sheppard</artist>
</song>
then:
<?php
$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

limitcracker
- 2,208
- 3
- 24
- 23
2
$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);
print_r($arr);

Dipanjan
- 29
- 3
-
2download_page(), really? At least when you suggest a function, stick to built-ins or define those you are proposing. Newbies can easily get lost. I suggest you edit this and replace it with a simple file_get_contents() the least. – David Aug 15 '17 at 21:46
2
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: http://php.net/domxml

dusoft
- 11,289
- 5
- 38
- 44
-
I agree to that . But why are tags not shown. I do an echo . Is it because of browser? – Rakesh Feb 18 '09 at 16:29
-
yes, browser treats XML as (X)HTML, so if > or < is encountered, it is treated as normal tag... – dusoft Feb 18 '09 at 16:30
-
1
1
simple load xml file ..
$xml = @simplexml_load_string($retValuet);
$status = (string)$xml->Status;
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;
?>

Ganesh
- 149
- 1
- 4