dsdsm2016 2012-08-27 19:52
浏览 24
已采纳

XML到数组? [PHP]

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>

or

<Formula>
<formulaname>Basic</formulaname>
<movespeed>1</movespeed>
<box>4</box>
<chicken>3</chicken>
<ducks>1</ducks>
<cereal>2</cereal>
</Formula>

What I have tried:

$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..

  • 写回答

4条回答 默认 最新

  • dtwncxs3547 2012-08-27 19:59
    关注

    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}";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码