【问题标题】:Why is my XML Array not able to be called?为什么无法调用我的 XML 数组?
【发布时间】:2012-11-19 14:20:59
【问题描述】:

我正在尝试使用 PHP 调用 XML 数组,但无论出于何种原因,它都不能正确提供结果。 XML 看起来像这样一个 simpleXMLElement。

SimpleXMLElement 对象 ( [@attributes] => 数组 ( [版权] => 所有数据版权 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 中执行此操作时,它可以正常工作。我只想在停止数组中获取所有内容。

提前感谢所有帮助像我这样的初学者的专家

【问题讨论】:

    标签: php xml arrays


    【解决方案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 元素属性。

    如果你知道你要定位哪个&lt;stop&gt;元素,那么你可以直接获取:

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

    【讨论】:

    • 谢谢。这就是我刚才所做的!关于是否有更好的方法来查看 XML 而不是 Print_R 的任何想法?
    • 据我所知,没有官方说明,但为了调试,我在单个元素上使用 echo 而不是 print_r 整个对象。另一种选择是使用saveXML() 方法查看实际的XML。
    • 我会试试 saveXML() 函数。谢谢!
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多