抱歉,如果这似乎是一个简单的问题,但我已经开始在这上面扯头发了……
我有一个看起来像这样的 XML 文件...
<VAR VarNum="90">
<option>1</option>
</VAR>
我正在尝试获取VarNum。
到目前为止,我已经成功使用以下代码获取其他信息:
$xml=simplexml_load_file($file);
$option=$xml->option;
我只是无法获得 VarNum (我认为的属性值?)
谢谢!
您应该能够使用SimpleXMLElement::attributes()
试试这个:
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
这将显示第一个foo
元素的所有名称/值属性。它是一个关联数组,因此您也可以这样做:
$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
怎么用$xml['VarNum']
?
像这样 :
$str = <<<XML
<VAR VarNum="90">
<option>1</option>
</VAR>
XML;
$xml=simplexml_load_string($str);
$option=$xml->option;
var_dump((string)$xml['VarNum']);
(我使用过simplexml_load_string
是因为我已将您的 XML 粘贴到一个字符串中,而不是创建一个文件;在您的情况下,您所做的一切simplexml_load_file
都很好!)
会得到你
string '90' (length=2)
使用 simpleXML,您可以使用数组语法访问属性。
你必须转换为一个字符串来获取值,而不是实例SimpleXMLElement
例如,请参阅手册中基本用法的示例 #5 :-)
[0] => Array
(
[@attributes] => Array
(
[uri] => https://abcd.com:1234/abc/cst/2/
[id] => 2
)
[name] => Array
(
[first] => abcd
[last] => efg
)
[company] => abc SOLUTION
[email] => abc@xyz.com
[homepage] => WWW.abcxyz.COM
[phone_numbers] => Array
(
[phone_number] => Array
(
[0] => Array
(
[main] => true
[type] => work
[list_order] => 1
[number] => +919876543210
)
[1] => Array
(
[main] => false
[type] => mobile
[list_order] => 2
[number] => +919876543210
)
)
)
[photo] => Array
(
[@attributes] => Array
(
[uri] => https://abcd.com:1234/abc/cst/2/cust_photo/
)
)
)
我应用了以下代码
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);
但它没有使用完整我想要php中单个数组中的所有数据
试试这个
$xml->attributes()['YourPropertyName']; //check property case also