How to Extract Value from SimpleXMLElement Object
When interacting with XML data in PHP, you may encounter instances where the data is structured within SimpleXMLElement objects. Accessing values from these objects requires specific techniques.
Consider the following scenario: You have an XML file that you have loaded into a SimpleXMLElement object named $xml, and you want to extract the value of a lat attribute within the XML code.
$url = "http://ws.geonames.org/findNearbyPostalCodes?country=pl&placename="; $url .= rawurlencode($city[$i]); $xml = simplexml_load_file($url); $cityCode[] = array( 'city' => $city[$i], 'lat' => $xml->code[0]->lat, 'lng' => $xml->code[0]->lng );
If you attempt to access the lat attribute directly as $xml->code[0]->lat, you will receive an object. To obtain the actual value, you need to cast the SimpleXMLElement object to a string.
$value = (string) $xml->code[0]->lat;
By casting the object to a string, you can then access the value of the lat attribute. This technique is applicable to any element or attribute within a SimpleXMLElement object.
The above is the detailed content of How to Extract Attribute Values from a PHP SimpleXMLElement Object?. For more information, please follow other related articles on the PHP Chinese website!