Le fait d’utiliser des fichiers XML générés par d’autres sites impliquent de traiter le Cross Scripting. En effet, le protocole internet interdit de récupérer des données XML en provenance de sites autres que le serbeur hébergeant la page qui effectue la requête.
Une solution simple consiste en l’utilisation de YQL (Yahoo! Developer Network)
L’exemple JS fidle qui lit un XML en provenance d’un site externe puis qui le transforme en JSON est ici : http://jsfiddle.net/AndroLogiciels/sMavF/43/
La page web de demo est la suivante (le zip https://app.box.com/s/gxavrpokdaxt7o6ydt3l contient le fichier jquery.js et la page)
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>XML 2 JSON</title>
</head>
<body>
<script src="jquery.js"></script>
<script>
//-- Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
//sample site that returns xml
site ='http://data.nantes.fr/api/getInfoTraficTANTempsReel/1.0/39W9VSNCSASEOGV';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent('select * from xml where url="' +
site + '"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON(yql, function (data) {
//console.log(data.results[0]);
var xml = $.parseXML(data.results[0]),
$xml = $( xml ),
$test = $xml.find('RESUME');
var jsonObj = JSON.stringify(xmlToJson(xml));
//-- Affichage dans la console de l'objet jSON
//console.log(jsonObj);
//-- Retourne l'objet JSON
return (document.write(jsonObj));
});
</script>
Le résultat visible dans la console de développement (sous chrome : Outils / Console Javascript ou Ctrl + maj + J) ou sur la page web
En php :
<?php
//$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);
?>
Votre commentaire