php 从 SimpleXMLElement 对象获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2867575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:58:06  来源:igfitidea点击:

Get value from SimpleXMLElement Object

phpsimplexml

提问by kubas

I have something like this:

我有这样的事情:

$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
);

It's supposed to download XML from geonames. If I do print_r($xml)I get :

它应该从 geonames 下载 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
                )

I do as you can see $xml->code[0]->latand it returns an object. How can i get the value?

我如你所见$xml->code[0]->lat,它返回一个对象。我怎样才能获得价值?

回答by Luis Melgratti

You have to cast simpleXML Object to a string.

您必须将 simpleXML Object 转换为字符串。

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

回答by sglessard

You can also use the magic method __toString()

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

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

回答by CoursesWeb

If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)

如果您知道 XML 元素的值是一个浮点数(纬度、经度、距离),则可以使用 (float)

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

Also, (int)for integer number:

另外,(int)对于整数:

$value = (int) $xml->code[0]->distance;

回答by vladkras

if you don'tknow the value of XML Element, you can use

如果你知道 XML Element 的值,你可以使用

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

if (ctype_digit($value)) {
    // the value is probably an integer because consists only of digits
}

It works when you need to determine if value is a number, because (string)will always return string and is_int($value)returns false

当您需要确定 value 是否为数字时,它会起作用,因为(string)将始终返回字符串并is_int($value)返回false

回答by dazzafact

For me its easier to use arrays than objects,

对我来说,数组比对象更容易使用,

So, I convert an Xml-Object,

所以,我转换了一个 Xml 对象,

$xml = simplexml_load_file('xml_file.xml');    
$json_string = json_encode($xml);    
$result_array = json_decode($json_string, TRUE);

回答by pal4life

This is the function that has always helped me convert the xml related values to array

这是一直帮助我将 xml 相关值转换为数组的函数

function _xml2array ( $xmlObject, $out = array () ){
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? _xml2array ( $node ) : $node;

    return $out;
}

回答by Bendeberia

try current($xml->code[0]->lat)

尝试 current($xml->code[0]->lat)

it returns element under current pointer of array, which is 0, so you will get value

它返回数组当前指针下的元素,即0,因此您将获得值

回答by Zakaria Charik

you can use the '{}' to access you property, and then you can do as you wish. Save it or display the content.

您可以使用“{}”访问您的属性,然后您可以随心所欲。保存或显示内容。

    $varName = $xml->{'key'};

From your example her's the code

从你的例子中,她是代码

        $filePath = __DIR__ . 'Your path ';
        $fileName = 'YourFilename.xml';

        if (file_exists($filePath . $fileName)) {
            $xml = simplexml_load_file($filePath . $fileName);
            $mainNode = $xml->{'code'};

            $cityArray = array();

            foreach ($mainNode as $key => $data)        {
               $cityArray[..] = $mainNode[$key]['cityCode'];
               ....

            }     

        }

回答by craned

$codeZero = null;
foreach ($xml->code->children() as $child) {
   $codeZero = $child;
}

$lat = null;
foreach ($codeZero->children() as $child) {
   if (isset($child->lat)) {
      $lat = $child->lat;
   }
}

回答by nixis

you can convert array with this function

你可以用这个函数转换数组

function xml2array($xml){
$arr = array();

foreach ($xml->children() as $r)
{
    $t = array();
    if(count($r->children()) == 0)
    {
        $arr[$r->getName()] = strval($r);
    }
    else
    {
        $arr[$r->getName()][] = xml2array($r);
    }
}
return $arr;
}