为什么getElementsByTagName()对我不起作用?

时间:2015-06-21 23:59:14

标签: php xml xml-parsing domdocument

我正在尝试从OMDb API获取信息。我发现了一些代码,但它无法正常工作:

$loc = 'http://www.omdbapi.com/?t='.$lookup_title.'&r=xml';
$dom = new DOMDocument();  
$dom->load($loc);  
foreach ($dom->getElementsByTagName('movie') as $e) {

    $imdb = $e->getElementsByTagName('imdbID')->item(0)->textContent; 
    $year = $e->getElementsByTagName('year')->item(0)->textContent;  
    $plot = $e->getElementsByTagName('plot')->item(0)->textContent; 
    $poster = $e->getElementsByTagName('poster')->item(0)->textContent;   

}  

OMDb API的XML输出:

<?xml version="1.0" encoding="UTF-8"?>
<root response="True">
  <movie title="Terminator 2: Judgment Day"
         year="1991"
         rated="R"
         released="03 Jul 1991"
         runtime="137 min"
         genre="Action, Sci-Fi"
         director="James Cameron"
         writer="James Cameron, William Wisher Jr."
         actors="Arnold Schwarzenegger, Linda Hamilton, Edward Furlong, Robert Patrick"
         plot="Almost 10 years have passed since the first cyborg called The Terminator tried to kill Sarah Connor and her unborn son, John Connor. John Connor, the future leader of the human resistance, is now a healthy young boy. However another Terminator is sent back through time called the T-1000, which is more advanced and more powerful than its predecessor. The Mission: to kill John Connor when he's still a child. However, Sarah and John do not have to face this threat of a Terminator alone. Another Terminator is also sent back through time. The mission: to protect John and Sarah Connor at all costs. The battle for tomorrow has begun..."
         language="English, Spanish"
         country="USA, France"
         awards="Won 4 Oscars. Another 20 wins &amp; 21 nominations."
         poster="http://ia.media-imdb.com/images/M/MV5BMTg5NzUwMDU5NF5BMl5BanBnXkFtZTcwMjk2MDA4Mg@@._V1_SX300.jpg"
         metascore="68"
         imdbRating="8.5"
         imdbVotes="636,472"
         imdbID="tt0103064"
         type="movie"/>
</root>

错误

  

注意:尝试获取非对象的属性

1 个答案:

答案 0 :(得分:3)

imdbyearplotposter部分是XML 属性,而非元素,所以请使用DOMElement::getAttribute()而不是getElementsByTagName()

$imdb = $e->getAttribute('imdbID'); 
$year = $e->getAttribute('year');  
$plot = $e->getAttribute('plot'); 
$poster = $e->getAttribute('poster');