Home > Backend Development > PHP Tutorial > How to Retrieve Attribute Values from XML in PHP?

How to Retrieve Attribute Values from XML in PHP?

Linda Hamilton
Release: 2024-11-19 02:17:02
Original
373 people have browsed it

How to Retrieve Attribute Values from XML in PHP?

Getting Attribute Values from XML in PHP

Retrieving attribute values from an XML file can be a straightforward task in PHP using the SimpleXMLElement class.

Suppose you have an XML file that resembles this:

<VAR VarNum="90">
  <option>1</option>
</VAR>
Copy after login

To obtain the value of the VarNum attribute, you can leverage the attributes() method of the SimpleXMLElement object.

$xml = simplexml_load_file($file);
foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) {
    echo "$attributeName=\"$attributeValue\"\n";
}
Copy after login

This code iterates through all the attributes of the first Var element and prints their names and values in a structured format.

Alternatively, you can directly access the attribute value by name:

$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
Copy after login

The above is the detailed content of How to Retrieve Attribute Values from XML in PHP?. 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