简体   繁体   中英

PHP Retrieve DATA from XML

My first attempt at retrieving data from XML for a maps application has failed. Here is a piece of the XML Feed.

<?xml version="1.0" encoding="UTF-8"?>
<DirectionsResponse>
 <status>OK</status>
 <route>
  <leg>

   <start_address>Winkfield, Bracknell, Berkshire RG42 6LY, UK</start_address>
   <end_address>Wentworth, Surrey GU25 4, UK</end_address>

  </leg>
 </route>
</DirectionsResponse>

I want to get the start and end address and return them via AJAX to the application.

The PHP

<?php 

$start = $_POST['start'];
$end = $_POST['end'];

$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$end.'&sensor=false');


// data to fetch

$start = $xml->xpath("/DirectionsResponse/route/leg/start_address");

$end = $xml->xpath("/DirectionsResponse/route/leg/end_address");

$start = array($start);
// output

echo json_encode( array('output'=>$start[0]));


?>

Annoyingly this is returning an object to the page.

Response:: {"output":[{"0":"Winkfield, Windsor, Berkshire SL4 2ES, UK"}]}

Anyone know how to stop that from happening. I just want the value Winkfield, Windsor, Berkshire SL4 2ES, UK.

Haven't tested your specific case, but i remember running into something similar when using SimpleXML, you might want to use (string) to cast it out of the object

array('output'=> (string)$start[0])

Or rather just leave out $start = array($start) and just do

array('output'=> (string)$start)

On reading the SimpleXML XPath documentation (http://www.php.net/manual/en/simplexmlelement.xpath.php) again i think your problem might be this:

Returns an array of SimpleXMLElement objects or FALSE in case of an error.

So the XPath returns an array, then you wrap that in an array and take the first element of that array, so all you end up with is the original array - remove the array wrap and you should be fine

function XMLReader()
{
    $MyArray = array();

    $doc = new DOMDocument(); 
    $doc->load( 'XMLFilePath.xml' ); 
    $info = $doc->getElementsByTagName( "leg" );
    foreach( $info as $Type )
    {
        $details = $Type->getElementsByTagName( "start_address" );
        $detail = $details->item(0)->nodeValue;     
        $MyArray [] = $detail; 
    }

    return $MyArray;
}

and same for end_Address. I wish this answer is helpful.

echo $xml->route->leg->start_address;

This is the edited answer. I checked it. Its working properly on the XML.

Just echo $start? Also, why do you make an array of start and then output the first element, it doesnt make any sense at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM