使用php解析xml并将其转换为json以与$.ajax一起使用时遇到问题


trouble parsing xml and converting it to json with php for use with $.ajax

我正试图使用php从API获取xml。到目前为止,我已经看了下面的博客文章和之前的stackoverflow文章,但没有成功。

通过查看网页的源代码,可以在此处获得xml数据。

根据我的理解,php的json_encodestring(length)为前缀的字符串形式返回json数据。

我想做的是用JQuery的$.ajax加载编码的json数据,以使用javascript操作数据。然而,php的json_encode返回的数据与$.ajax不兼容。

有人对如何格式化字符串以便ajax读取数据有什么建议吗?

更新,我的代码php代码在这里:

<?php        
    $url = file_get_contents("http://api.wefeelfine.org:8080/ShowFeelings?display=xml&returnfields=sentence&limit=50");
    $simpleXml = simplexml_load_string($url);
    $json = json_encode($simpleXml);
    var_dump($json);
?>

我使用php进行跨域请求,然后使用$.ajax的php代码的url。当使用$.aajax访问API的url而不使用php时,我会得到No 'Access-Control-Allow-Origin'错误。

json_encode不会在SimpleXMLElement对象上工作,至少不会像您预期的那样

$feelings = array();
foreach($simpleXml as $feeling) {
    $feelings[] = array('sentence' => $feeling['sentence'] . '');
}
$json = json_encode($feelings);