Home >Backend Development >PHP Tutorial >How to Extract Attribute Values from a PHP SimpleXMLElement Object?

How to Extract Attribute Values from a PHP SimpleXMLElement Object?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 03:20:141042browse

How to Extract Attribute Values from a PHP SimpleXMLElement Object?

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!

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