2017-02-01 11 views
0

omdb APIから映画のタイトルと情報を取得しようとしています。これは私のコードです:OMDb APIからのデータをxmlで取得

<?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からデータを得ることができますか?

はあなたは、その要素にアクセスする方法を知っているXMLの構造を理解しておく必要があり、 ジュリアン

答えて

0

、ありがとうございました。だから、あなたがから選択する必要が結果を配列で受け取る

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/[email protected]@._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/[email protected]_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/[email protected]@._V1_SX300.jpg 
         ) 

       ) 

     ) 

) 

print_r(get_object_vars($xml))はあなたにこのような構造が表示されます。あるいは、正確なタイトルを知っている場合は、APIにt=titleオプションがあり、結果は1つのみ返されます(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"; 
} 
?> 
関連する問題