如何从 PHP 中的 XML 文件中获取属性的值? [英] How to get the value of an attribute from XML file in PHP?
本文介绍了如何从 PHP 中的 XML 文件中获取属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
抱歉,这似乎是一个简单的问题,但我已经开始在这个问题上扯头发了...
Sorry if this seems like an easy question, but I've started pulling hair out on this...
我有一个像这样的 XML 文件...
I have a XML file which looks like this...
<VAR VarNum="90">
<option>1</option>
</VAR>
我正在尝试获取 VarNum.
到目前为止,我已成功使用以下代码获取其他信息:
So far I've been successful using the follow code to get the other information:
$xml=simplexml_load_file($file);
$option=$xml->option;
我就是无法获得 VarNum(我认为的属性值?)
I just can't get VarNum (the attribute value I think?)
谢谢!
推荐答案
您应该能够使用 SimpleXMLElement::attributes()
试试这个:
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,""
";
}
这将显示第一个 foo
元素的所有名称/值属性.这是一个关联数组,因此您也可以这样做:
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'];
这篇关于如何从 PHP 中的 XML 文件中获取属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文