PHP 从 XML 中检索数据 [英] PHP Retrieve DATA from XML

查看:27
本文介绍了PHP 从 XML 中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次尝试从 XML 检索地图应用程序的数据失败了.这是 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>

我想获取开始和结束地址,并通过 AJAX 将它们返回给应用程序.

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

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.

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

任何人都知道如何阻止这种情况发生.我只想要价值 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.

推荐答案

尚未测试您的具体情况,但我记得在使用 SimpleXML 时遇到了类似的情况,您可能想使用 (string) 将其从对象

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])

或者只是省略 $start = array($start) 而只是做

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

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

再次阅读 SimpleXML XPath 文档 (http://www.php.net/manual/en/simplexmlelement.xpath.php) 时,我认为您的问题可能是这样的:

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.

所以 XPath 返回一个数组,然后你将它包装在一个数组中并取该数组的第一个元素,所以你最终得到的是原始数组 - 删除数组包装,你应该没问题

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

这篇关于PHP 从 XML 中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆