Home >Backend Development >PHP Tutorial >How to Retrieve Values from a SimpleXMLElement Object in PHP?
Retrieving Values from SimpleXMLElement Objects
You may encounter situations where you need to extract specific values from XML data stored in SimpleXMLElement objects. This article will guide you through a scenario where you have XML data obtained from a remote source and show you how to access the desired values from the object.
The Issue
Consider the following code snippet:
$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, // Returns an object 'lng' => $xml->code[0]->lng );
As you can see, accessing the 'lat' property of the object $xml->code[0]->lat returns an object, making it challenging to retrieve the actual value.
The Solution
To retrieve the value from an object, you need to cast it to a string. Here's how you can do it:
$value = (string) $xml->code[0]->lat;
By casting the object to a string, you can access the value as desired.
The above is the detailed content of How to Retrieve Values from a SimpleXMLElement Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!