Читать XML PHP DOM с XPATH - PullRequest
       11

Читать XML PHP DOM с XPATH

0 голосов
/ 04 ноября 2011

У меня есть вопрос.

У меня есть xml

http://maps.googleapis.com/maps/api/geocode/xml?address=new+york&sensor=true

Я хочу прочитать из примера

GeocodeResponse / result / geometry/ location / lat

и

GeocodeResponse / result / geometry / location / lng

возможно, используя XPATH, и это то, что у меня есть до сих пор ...

<?php

$Address = "new+york";
$Query = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
$XmlResponse = file_get_contents($Query);

$doc = new DOMDocument();
$doc->loadXML($XmlResponse);

$root = $doc->getElementsByTagName( "GeocodeResponse" );
foreach( $root as $val )
{
    $hrefs = $val->getElementsByTagName( "status" );
    $status = $hrefs->item(0)->nodeValue;

    foreach( $hrefs as $val2 )
    {
        $hrefs2 = $val2->getElementsByTagName( "type" );
        $type = $hrefs2->item(0)->nodeValue;

        echo "Type is: $type  <br>";
    }

    echo "Status is: $status  <br>";
}


?>

Могу ли я дать несколько советов?

возможно, я смогу использовать

$xpath = new DOMXPath($xml);
$hrefs = $xpath->evaluate("/page");

ОБНОВЛЕНИЕ !!

Мне удалось получить результат этим ...

$xpath = new DOMXPath($doc);
$res = $xpath->evaluate('//GeocodeResponse/result/geometry');

$root = $doc->getElementsByTagName( "location" );
foreach( $root as $val )
{
    $hrefs = $val->getElementsByTagName( "lat" );
    $status = $hrefs->item(0)->nodeValue;

    echo "Status is: $status  <br>";
}

, но я хочу что-то без foreach вроде

$xpath = new DOMXPath($doc);
$res = $xpath->evaluate('//GeocodeResponse/result/geometry');
$hrefs = $val->getElementsByTagName( "lat" );
$status = $hrefs->item(0)->nodeValue;

echo "Status is: $status  <br>";

Возможно ли это?

1 Ответ

1 голос
/ 04 ноября 2011

Возможно, вы захотите переключиться на JSON, который гораздо проще разобрать:

http://maps.googleapis.com/maps/api/geocode/json?address=new+york&sensor=true

$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=new+york&sensor=true');

$geocodeResponse = json_decode($json, true);

foreach($geocodeResponse['results'] as $result){
   echo $result['geometry']['location']['lat'].', '.$result['geometry']['location']['lng'] .'<br>';
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...