1

PHP を使用して XML 配列を呼び出そうとしていますが、何らかの理由で結果が適切に提供されません。XML は simpleXMLElement として次のようになります。

SimpleXMLElement オブジェクト ( [@attributes] => 配列 ( [copyright] => All data copyright 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 でこれを行うと、正常に動作します。停止配列のみですべてを取得したいと思います。

私のような初心者を助けてくれたすべての専門家に事前に感謝します

4

1 に答える 1

1

Using print_r on SimpleXML elements does not always give you the full picture. Your elements are there but aren't shown.

$xml->route->stop is an array of <stop> tags within <route>. So if you want to loop through each stop tag then:

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

In the loop, $stop is a SimpleXML element, so in order to print its value you can cast the whole element as a string using the (string) syntax. You can still access attributes and other SimpleXML element properties.

If you know which <stop> element you want to target, then you can get it directly:

echo (string)$xml->route->stop[1]; // prints the second <stop> value
于 2012-11-19T14:27:24.697 に答える