我有一个名为bookscript的PHP页面.php致力于将Goodreads API结果从XML格式转换为JSON格式:
<?php
$xml_string = file_get_contents("https://www.goodreads.com/search?q=" .$_REQUEST['search']. "&search%5Bfield%5D=title&format=xml&key=ZuqW9sL15d3JvEwmLyaNCg");
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
echo $json;
?>
在我的主页上,我将 bookscript.php 插入到这个 AJAX 调用中:
function GetBooks(request) {
//Replace spaces with a '+'
var url = request.term.replace(/'s/g,"+");
return $.ajax({
'url': "php/bookscript.php?search=" + url,
'dataType': 'json'
}).then(function(data){
return $.map(data.results || [], function(v,i){
return {
label: v.work.title + ' BOOK (' + v.work.original_publication_year + ')',
value: v.work.title
}
});
})
但这行不通。当我访问 http://www.example.com/php/bookscript.php?search=dog 时,页面上显示的只是"假"字。
将此结果与Goodreads的实际结果进行比较:https://www.goodreads.com/search/index.xml?&key=ZuqW9sL15d3JvEwmLyaNCg&q=dog
所以我的问题是...我的方法出了什么问题?我确实在我的网站上有 SSL 工作(不确定这是否相关(,所以应该排除这是问题......
我确实知道 GET 请求代码应该是有效的,因为相同的代码适用于使用 JSON 格式的其他 API。
编辑:问题实际上是我的服务器上没有安装PHP。 =(
我已经用这段代码进行了测试,一切都很好,
<?php $xml_string = file_get_contents("https://www.goodreads.com/search?q=dog&search%5Bfield%5D=title&format=xml&key=ZuqW9sL15d3JvEwmLyaNCg");
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);?>
<pre>
<?php print_r($array); ?>
</pre>
阵列打印如下:
Array
(
[Request] => Array
(
[authentication] => true
[key] => Array
(
)
[method] => Array
(
)
)
[search] => Array
(
[query] => Array
(
)
[results-start] => 1
[results-end] => 20
[total-results] => 26080
[source] => Goodreads
[query-time-seconds] => 0.31
[results] => Array
(
[work] => Array
(
[0] => Array
(
[id] => 10479953
[books_count] => 38...
也许您的客户端出错了?ajax 调用的结果是什么?
json_encode
需要一个具有公共属性的数组或对象作为输入。如果失败,则返回布尔false
。 simplexml_load_string
返回一个SimpleXMLElement
。
您需要遍历SimpleXMLElement
并从中创建数组,或者查找为您执行此操作的函数或类。您可以在互联网上找到大量实现。
看到这个SO答案:https://stackoverflow.com/a/20431742/1479962