2011-01-11 57 views
1

我此刻的下面的代码:PHP的DOMDocument变量

$ip = '195.72.186.157'; 

$xmlDoc = new DOMDocument(); 
$xmlDoc->loadXML(file_get_contents('http://www.geoffmeierhans.com/services/geo-locator/locate/?ip='.$ip.'&output=xml')); 

foreach($xmlDoc->getElementsByTagName('city') as $link) { 
    $links = array('text' => $link->nodeValue); 
} 
$city = $links['text']; 
echo $city; 

有没有更好的办法让城市变?由于只有所谓的城市一个标签是不是真的需要一个循环,但我不能让它开始工作任何其他方式

+0

*(TIPP)*`的DOMDocument :: load`可以加载远程文件。 – Gordon 2011-01-11 15:47:14

回答

4

好了,你可以使用length参数DomNodeList(什么是由getElementsByTagName调用返回。

如果你只想要第一个结果:

$nodes = $xmlDoc->getElementsByTagName('city'); 
if ($nodes->length > 0) { 
    $city = $nodes->item(0)->nodeValue; 
} else { 
    $city = ''; // There is no city element 
}