从 SimpleXMLElement Object 中获取价值

2022-08-30 06:16:22

我有这样的东西:

$url = "http://ws.geonames.org/findNearbyPostalCodes?country=pl&placename=";
$url .= rawurlencode($city[$i]);

$xml = simplexml_load_file($url);
echo $url."\n";
$cityCode[] = array(
    'city' => $city[$i], 
    'lat' => $xml->code[0]->lat, 
    'lng' => $xml->code[0]->lng
);

它应该从地名下载XML。如果我这样做,我会得到:print_r($xml)

SimpleXMLElement Object
(
    [code] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [postalcode] => 01-935
                    [name] => Warszawa
                    [countryCode] => PL
                    [lat] => 52.25
                    [lng] => 21.0
                    [adminCode1] => SimpleXMLElement Object
                        (
                        )

                    [adminName1] => Mazowieckie
                    [adminCode2] => SimpleXMLElement Object
                        (
                        )

                    [adminName2] => Warszawa
                    [adminCode3] => SimpleXMLElement Object
                        (
                        )

                    [adminName3] => SimpleXMLElement Object
                        (
                        )

                    [distance] => 0.0
                )

我按照你所看到的去做,它返回一个对象。如何获取价值?$xml->code[0]->lat


答案 1

您必须将 simpleXML 对象强制转换为字符串。

$value = (string) $xml->code[0]->lat;

答案 2

您也可以使用魔术方法__toString()

$xml->code[0]->lat->__toString()

推荐