尝试使用此代码。
使用函数转换XML 2 JSON
此处示例:
<?php
class XmlToJson {
public static function Parse($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("'n", "'r", "'t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
$getXML = "http://api.devstate.de/json/divisas.xml";
print XmlToJson::Parse($getXML);
?>
(顺便说一句,原始代码有一些格式错误的JSON问题,所以我们在函数中添加了strict)
在这一步之前,似乎一切都正常。
我们得到了一个有效的JSON,但当我们试图通过jQuery或Angular调用它时,我们总是得到一个UNDEFINED数据。
如果我使用:
$(document).ready(function() {
$.getJSON('convertedXML.php', function(json) {
console.log(json.row);
});
});
我得到:
https://www.dropbox.com/s/oq5a8av2etcwvo3/Screenshot%202015-04-08%2020.02.56.png
但是json.row.$WHATTHEHELL.Divisa呢
什么都没有发生,什么都没有返回UNDEFINED
你觉得怎么样,我们做错了什么。
感谢
在$.getJSON
块中,如果您得到了正确的响应,那么只需使用$.each
在其中迭代:
$.each(json.row, function(i, e){
console.log(e['@attributes'].Divisa); // and other properties
});
示例演示
@Ghost这个解决方案太棒了!谢谢
只是,这里有任何简化的建议:
<div>
<ul id="currency-USD">
<li class="currency-USD--name"></li>
<li class="currency-USD--buy"></li>
<li class="currency-USD--sell"></li>
</ul>
<ul id="currency-UE">
<li class="currency-UE--name"></li>
<li class="currency-UE--buy"></li>
<li class="currency-UE--sell"></li>
</ul>
<ul id="currency-CAD">
<li class="currency-CAD--name"></li>
<li class="currency-CAD--buy"></li>
<li class="currency-CAD--sell"></li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: document.URL,
type: 'POST',
dataType: 'JSON',
success: function(json) {
var group = json.row;
// alert('check the browser console');
$('.currency-USD--name').html(group[0]['@attributes'].Divisa);
$('.currency-USD--buy').html(group[0]['@attributes'].Compra);
$('.currency-USD--sell').html(group[0]['@attributes'].Venta);
$('.currency-UE--name').html(group[1]['@attributes'].Divisa);
$('.currency-UE--buy').html(group[1]['@attributes'].Compra);
$('.currency-UE--sell').html(group[1]['@attributes'].Venta);
$('.currency-CAD--name').html(group[2]['@attributes'].Divisa);
$('.currency-CAD--buy').html(group[2]['@attributes'].Compra);
$('.currency-CAD--sell').html(group[2]['@attributes'].Venta);
// console.log(group[0]['@attributes'].Divisa);
}
});
});
</script>