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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,