XML到阵列? [PHP] [英] XML to Array? [PHP]
问题描述
嗯,我一直有改变的XML回到一个数组问题....这将如果每个XML遵循相同的格式,但每个XML是例外不同的是简单的<公式>
标签,formulaname和移动速度
例如:
Well I been having issues changing an xml back into an array....It would be simple if each xml followed the same format but every XML is different with the exception of the <Formula>
tag, formulaname and movespeed
ex:
<Formula>
<formulaname>Basic</formulaname>
<movespeed>1</movespeed>
<str>4</str>
<dex>3</dex>
<int>1</int>
<will>2</will>
</Formula>
或
<Formula>
<formulaname>Basic</formulaname>
<movespeed>1</movespeed>
<box>4</box>
<chicken>3</chicken>
<ducks>1</ducks>
<cereal>2</cereal>
</Formula>
我曾尝试:
$xml = simplexml_load_file("test.xml");
print_r($xml);
这实际上打印
的东西,但我不能让过去的,甚至回声
吧..
This actually prints
something but I couldn't get past that or even echo
it..
foreach($xml->text as $string) {
print_r($string);
echo 'attributes: '. $string->attributes() .'<br />';
}
没有工作,原来它是字符串
,但他们都不是字符串
...
Didn't work, originally it's for strings
but none of them are strings
...
foreach ($xml->Formula as $element) {
foreach($element as $key => $val) {
echo "{$key}: {$val}";
}
也不能工作,我需要这样的工作,所以我可以从使用的值数组
不知道究竟该值将被称为..
Didn't work either, I needed something like this to work so I can use the values from the array
without knowing what exactly the value will be called..
推荐答案
您无法使用节点本身上一个foreach访问的孩子,你需要使用。孩子()
:
You can't access children by using a foreach on the node itself, you need to use .children()
:
$s =<<<EOS
<root>
<Formula>
<formulaname>Basic</formulaname>
<movespeed>1</movespeed>
<box>4</box>
<chicken>3</chicken>
<ducks>1</ducks>
<cereal>2</cereal>
</Formula>
</root>
EOS;
$xml = simplexml_load_string($s);
foreach ($xml->Formula as $element) {
foreach($element->children() as $key => $val) {
echo "{$key}: {$val}";
}
}
这篇关于XML到阵列? [PHP]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!