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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 13:23:02127browse

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>

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

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";
}

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!

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