Get value from SimpleXMLElement Object

PhpSimplexml

Php Problem Overview


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 :

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]->lat and it returns an object. How can i get the value?

Php Solutions


Solution 1 - Php

You have to cast simpleXML Object to a string.

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

Solution 2 - Php

You can also use the magic method __toString()

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

Solution 3 - Php

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

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

Also, (int) for integer number:

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

Solution 4 - Php

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

$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

Solution 5 - Php

For me its easier to use arrays than objects,

So, I convert an Xml-Object,

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

Solution 6 - Php

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

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

    return $out;
}

Solution 7 - Php

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

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

Solution 8 - Php

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'];
               ....
               
            }     
            
        }
        
        

Solution 9 - Php

header("Content-Type: text/html; charset=utf8");
$url  = simplexml_load_file("http://URI.com");

 foreach ($url->PRODUCT as $product) {  
	foreach($urun->attributes() as $k => $v) {
		echo $k." : ".$v.' <br />';
	}
	echo '<hr/>';
}

Solution 10 - Php

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;
}

Solution 11 - Php

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

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

Solution 12 - Php

foreach($xml->code as $vals )
{ 
    unset($geonames);
    $vals=(array)$vals;
    foreach($vals as $key => $value)
      {
        $value=(array)$value;
        $geonames[$key]=$value[0];
      }
}
print_r($geonames);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkubasView Question on Stackoverflow
Solution 1 - PhpLuis MelgrattiView Answer on Stackoverflow
Solution 2 - PhpsglessardView Answer on Stackoverflow
Solution 3 - PhpCoursesWebView Answer on Stackoverflow
Solution 4 - PhpvladkrasView Answer on Stackoverflow
Solution 5 - PhpdazzafactView Answer on Stackoverflow
Solution 6 - Phppal4lifeView Answer on Stackoverflow
Solution 7 - PhpBendeberiaView Answer on Stackoverflow
Solution 8 - PhpZakaria CharikView Answer on Stackoverflow
Solution 9 - PhpŞahin SolmazView Answer on Stackoverflow
Solution 10 - PhpnixisView Answer on Stackoverflow
Solution 11 - PhpcranedView Answer on Stackoverflow
Solution 12 - PhpAmal Jo AntonyView Answer on Stackoverflow