J'appelle PHP méthode cURL sur un serveur et la réponse est de type XML. CURL enregistre la sortie (après avoir supprimé les balises) dans une variable de type scalaire. Existe-t-il un moyen de le stocker dans un objet/hachage/tableau afin qu'il soit facile à analyser?
<?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";
}
Ajoutez simplement header('Content-type: application/xml');
avant votre écho de la réponse XML et vous verrez une page XML.
Exemple:
<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>
puis:
<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>
Sortie sur votre navigateur: Navire des nomades
crédits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
$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);
non, CURL n'a rien avec l'analyse XML, il ne sait rien du contenu retourné. il sert de proxy pour obtenir du contenu. c'est à vous d'en faire quoi.
utilisez JSON si possible (et json_decode) - il est plus facile de travailler avec, sinon possible, utilisez n'importe quelle bibliothèque XML pour le parsin comme DOMXML: http://php.net/domxml
fichier xml simple chargement ..
$xml = @simplexml_load_string($retValuet);
$status = (string)$xml->Status;
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;
?>