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
Release: 2024-12-09 03:20:14
Original
974 people have browsed it

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
);
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template