Master345
Master345

Reputation: 2266

Read XML PHP DOM with XPATH

I have a question.

I have the xml

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

I want to read from example

GeocodeResponse/result/geometry/location/lat

and

GeocodeResponse/result/geometry/location/lng

maybe using XPATH and this is what i have so far ...

<?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>";
}


?>

Can i have some advices?

maybe i can use

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

UPDATE!!

I have managed to get the result by this ...

$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>";
}

but i want something without foreach like

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

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

Is this possible?

Upvotes: 0

Views: 760

Answers (1)

dev-null-dweller
dev-null-dweller

Reputation: 29462

You may want to switch to JSON that is much easier to parse:

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>';
}

Upvotes: 1

Related Questions