Home > Backend Development > PHP Tutorial > How to Access XML Attribute Values Using PHP\'s SimpleXMLElement?

How to Access XML Attribute Values Using PHP\'s SimpleXMLElement?

Barbara Streisand
Release: 2024-11-17 13:23:02
Original
220 people have browsed it

How to Access XML Attribute Values Using PHP's SimpleXMLElement?

Accessing Attribute Values from an XML File in PHP

When working with XML files in PHP, retrieving attribute values can be a common task. Let's consider the example XML:

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

Getting Attribute Values with SimpleXMLElement

To get the "VarNum" attribute value, we can utilize the SimpleXMLElement::attributes() method. Here's how:

$xml = simplexml_load_file($file);
$attr = $xml->Var->attributes();
echo $attr['VarNum']; // Output: 90
Copy after login

Looping through All Attributes

If you need to process multiple attributes, you can loop through the attributes() array:

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

Additional Note

Remember that attributes are accessed using the array syntax (['VarNum') rather than dot syntax.

The above is the detailed content of How to Access XML Attribute Values Using PHP\'s SimpleXMLElement?. 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