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>
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"; }
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'];
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!