2011-01-11 37 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 
}