douhe2305 2014-08-29 14:54
浏览 66
已采纳

在PHP中读取XML的一个节点

I have been searching for how to read one node of XML in PHP. The PHP documentation wasn't helpful because I don't understand how to use PHP. All of the tutorials I found weren't useful beacause I only need PHP to read XML(I use CSHTML for Databases and other server-side things). I have working code that can read XML as a tree if it is in a RSS format. I am trying to get the google map geocode api information, from "http://maps.googleapis.com/maps/api/geocode/xml?latlng=38.7876639,-90.8455276&sensor=false." I only want the very first "Formatted_address" node. My current code is;

<?php
$xml=("http://maps.googleapis.com/maps/api/geocode/xml?latlng=38.7876639,-90.8455276&sensor=false");

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get and output "<result>" elements
$x=$xmlDoc->getElementsByTagName('result');
for ($i=0; $i<=2; $i++)
  {
  $item=$x->result($i)->getElementsByTagName('formatted_address')
  ->result(0)->childNodes->result(0)->nodeValue;

  echo ( $item);
  }
?>

However this always returns a 500 error and I don't understand what i am doing wrong. Thank you all in advance.

  • 写回答

1条回答 默认 最新

  • dtdr84101 2014-08-29 15:00
    关注

    Change result to item

    $item = $x->item($i)->getElementsByTagName('formatted_address')
              ->item(0)->childNodes->result(0)->nodeValue;
    

    As you can see DOMNodeList only has one method called item(int $index)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?