我试着从omdb API获取电影标题和信息。这是我的代码:
<?php
$enter = $_GET["enter"];
$content = file_get_contents("https://www.omdbapi.com/?s=$enter&r=xml");
$xml = simplexml_load_string($content);
if($xml) {
echo "<h2>" .$xml->title. "</h2>";
}
else
{
echo "Nothing found. Add the info manualy";
}
?>
“输入”值来自使用AJAX的搜索表单。他只创建一个空的h2标签。我如何从API中获取数据?
谢谢你, 儒略
答案 0 :(得分:0)
您应该熟悉xml的结构,以了解如何访问其元素。 print_r(get_object_vars($xml))
会向您显示如下结构:
Array
(
[@attributes] => Array
(
[totalResults] => 3651
[response] => True
)
[result] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => World War Z
[year] => 2013
[imdbID] => tt0816711
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0NTgxMjIxOF5BMl5BanBnXkFtZTcwMDM0MDY1OQ@@._V1_SX300.jpg
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => Captain America: Civil War
[year] => 2016
[imdbID] => tt3498820
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMjQ0MTgyNjAxMV5BMl5BanBnXkFtZTgwNjUzMDkyODE@._V1_SX300.jpg
)
)
...
...
...
[9] => SimpleXMLElement Object
(
[@attributes] => Array
(
[title] => War
[year] => 2007
[imdbID] => tt0499556
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMTgzNTA4MTc3OF5BMl5BanBnXkFtZTcwOTA0ODk0MQ@@._V1_SX300.jpg
)
)
)
)
因此,您会收到一个数组,其中包含您需要选择的结果。或者,如果您知道API具有t=title
选项的确切标题,该选项仅返回单个结果(请参阅documentation)。
因此,假设您使用返回多个结果的s=title
选项,您可以使用类似的内容从第一个结果中选择信息:
<?php
$enter = $_GET["enter"];
$content = file_get_contents("https://www.omdbapi.com/?s=$enter&r=xml");
$xml = simplexml_load_string($content);
# show the structure of the xml
# print_r(get_object_vars($xml));
if($xml) {
print "<h2>" .$xml->result[0]['title']. "</h2>";
print "<br>imdbID=" . $xml->result[0]['imdbID'] ;
} else {
echo "Nothing found. Add the info manualy";
}
?>