Home >Backend Development >PHP Tutorial >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!