对不起,如果这看起来像一个简单的问题,但我已经开始对此发表了看法......
我有一个看起来像这样的XML文件......
<VAR VarNum="90">
<option>1</option>
</VAR>
我正在尝试获取 VarNum 。
到目前为止,我已成功使用以下代码获取其他信息:
$xml=simplexml_load_file($file);
$option=$xml->option;
我无法获得VarNum(我认为属性值?)
谢谢!
答案 0 :(得分:23)
您应该可以使用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'];
答案 1 :(得分:14)
如何使用$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
例如,请参阅手册中Basic usage的示例#5 : - )
答案 2 :(得分:1)
[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中的单个数组中的所有数据
答案 3 :(得分:0)
尝试一下
$xml->attributes()['YourPropertyName']; //check property case also