kubas
kubas

Reputation: 2381

Get value from SimpleXMLElement Object

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?

Upvotes: 238

Views: 293568

Answers (13)

Antony
Antony

Reputation: 4320

This question is quite old - I appreciate that, but I also discovered (in PHP 8.2) that you can use trim() on a SimpleXMLElement Object and whilst the input isn't technically a string, it will convert it! Not sure if that is a glitch with PHP as clearly its an object not a string but does work as of 2024.

Upvotes: -1

dazzafact
dazzafact

Reputation: 2860

Quick Solution if you in hurry.

convert a Xml-Object to an array (or object),

function loadXml2Array($file,$array=true){
   $xml = simplexml_load_file($file);   
 
   $json_string = json_encode($xml);    
   return json_decode($json_string, $array);
}

Upvotes: 16

Zakaria Charik
Zakaria Charik

Reputation: 119

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

            }     

        }

Upvotes: 4

craned
craned

Reputation: 3051

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

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

Upvotes: 0

nixis
nixis

Reputation: 510

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

Upvotes: 1

Bendeberia
Bendeberia

Reputation: 116

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

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

Upvotes: 2

pal4life
pal4life

Reputation: 3378

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

Upvotes: 3

Amal Jo Antony
Amal Jo Antony

Reputation: 39

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

Upvotes: -2

Şahin Solmaz
Şahin Solmaz

Reputation: 27

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

Upvotes: 1

vladkras
vladkras

Reputation: 17218

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

Upvotes: 17

CoursesWeb
CoursesWeb

Reputation: 4237

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;

Upvotes: 22

sglessard
sglessard

Reputation: 3156

You can also use the magic method __toString()

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

Upvotes: 107

Luis Melgratti
Luis Melgratti

Reputation: 12050

You have to cast simpleXML Object to a string.

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

Upvotes: 494

Related Questions