How to get the value of an attribute from XML file in PHP?
Solution 1:
You should be able to get this using SimpleXMLElement::attributes()
Try this:
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
That will show you all the name/value attributes for the first foo
element. It's an associative array, so you can do this as well:
$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
Solution 2:
What about using $xml['VarNum']
?
Like this :
$str = <<<XML
<VAR VarNum="90">
<option>1</option>
</VAR>
XML;
$xml=simplexml_load_string($str);
$option=$xml->option;
var_dump((string)$xml['VarNum']);
(I've used simplexml_load_string
because I've pasted your XML into a string, instead of creating a file ; what you are doing with simplexml_load_file
is fine, in your case !)
Will get you
string '90' (length=2)
With simpleXML, you access attributes with an array syntax.
And you have to cast to a string to get the value, and not and instance of SimpleXMLElement
For instance, see example #5 of Basic usage in the manual :-)