Home >Backend Development >PHP Tutorial >How to Extract Attribute Values from XML in PHP?
Accessing Attribute Values from XML in PHP
Retrieving attribute values from an XML file in PHP can be straightforward using the simplexml_load_file() function and the attributes() method.
Question:
How can I obtain the value of the VarNum attribute from the following XML fragment:
<VAR VarNum="90"> <option>1</option> </VAR>
Answer:
To access the VarNum attribute, we can use the attributes() method as follows:
$xml = simplexml_load_file($file); foreach ($xml->Var[0]->attributes() as $attribute => $value) { echo "$attribute=\"$value\"\n"; }
This code iterates through all attributes of the first element and prints the attribute name and value pairs. To retrieve the VarNum attribute specifically, we can use:
$attr = $xml->Var[0]->attributes(); echo $attr['VarNum'];
The above is the detailed content of How to Extract Attribute Values from XML in PHP?. For more information, please follow other related articles on the PHP Chinese website!