【问题标题】:Why is getElementsByTagName() not working for me?为什么 getElementsByTagName() 对我不起作用?
【发布时间】:2015-09-07 08:19:59
【问题描述】:

我正在尝试从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>

错误

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

【问题讨论】:

    标签: php xml xml-parsing domdocument


    【解决方案1】:

    imdbyearplotposter 部分是 XML 属性,而不是 元素,因此请使用 DOMElement::getAttribute() 而不是 @ 987654326@:

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

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 1970-01-01
      • 2010-10-08
      • 2016-02-27
      • 2019-01-13
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多