2012-11-19 14 views
1

我想调用一个使用PHP的XML数组,但不管出于什么原因,它都不能正确提供结果。 XML看起来像是一个simpleXMLElement。为什么我的XML数组无法被调用?

SimpleXMLElement对象 ( [@属性] =>数组 ( [著作权] =>所有数据版权2012 )

[route] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [tag] => 385 
       [title] => 385-Sheppard East 
       [color] => ff0000 
       [oppositeColor] => ffffff 
       [latMin] => 43.7614499 
       [latMax] => 43.8091799 
       [lonMin] => -79.4111 
       [lonMax] => -79.17073 
      ) 

     [stop] => Array 
      (
       [0] => SimpleXMLElement Object 
        (
         [@attributes] => Array 
          (
           [tag] => 14798 
           [title] => Sheppard Ave East At Yonge St (Yonge Station) 
           [lat] => 43.7614499 
           [lon] => -79.4111 
           [stopId] => 15028 
          ) 

        ) 
       [1] => SimpleXMLElement Object 
        (
         [@attributes] => Array 
          (
           [tag] => 4024 
           [title] => Sheppard Ave East At Doris Ave 
           [lat] => 43.7619499 
           [lon] => -79.40842 
           [stopId] => 13563 
          ) 

        ) 

有几个部件到停止阵列。我的代码如下像这样:

$url = "this_url"; 
$content = file_get_contents($url); 
$xml = new SimpleXMLElement($content); 
$route_array = $xml->route->stop; 

当我打印$ route_array,那只能说明从站1分的记录,我需要通过一个循环,当我跑这通常?在JSON中这样做,它工作正常。我想只在停止数组中获得所有内容。

在此先感谢在座的各位专家在那里帮助了初学者像我这样的

回答

1

上的SimpleXML元素使用print_r并不总是给你的全貌。你的元素在那里,但没有显示。

$xml->route->stop<route><stop>标签的数组。所以,如果你通过每个停止标记要环路,则:

foreach($xml->route->stop as $stop) 
{ 
    echo (string)$stop; // prints the value of the <stop> tag 
} 

在循环中,$stop是SimpleXML的元素,所以为了打印出它的价值,就可以把整个元素作为使用(string)语法的字符串。您仍然可以访问属性和其他SimpleXML元素属性。

如果你知道你要指定的<stop>元素,那么你可以直接得到它:

echo (string)$xml->route->stop[1]; // prints the second <stop> value 
+0

感谢。这就是我刚刚做的!关于是否有更好的方式来查看XML而不是Print_R的任何想法? – user1701252

+0

据我所知,没有官方的说明,但要调试我在各个元素上使用echo而不是print_r整个对象。另一种选择是使用'saveXML()'方法来查看实际的XML。 – MrCode

+0

我会试一试saveXML()函数。谢谢! – user1701252

相关问题