Home >Backend Development >PHP Tutorial >How to Retrieve Values from a SimpleXMLElement Object in PHP?

How to Retrieve Values from a SimpleXMLElement Object in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 16:23:11224browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn