开发者

php domDocument variables

I have the following code at the moment:

$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('c开发者_开发百科ity') as $link) {
    $links = array('text' => $link->nodeValue);
} 
$city = $links['text'];
echo $city;

Is there a better way to get the city variable? Since there is only one tag called city a loop isn't really needed but I can't get it to work any other way


Well, you can use the length parameter to DomNodeList (what's returned by the getElementsByTagName call.

If you want only the first result:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜