【问题标题】:PHP - XML to Array'sPHP - XML 到数组的
【发布时间】:2018-01-03 15:47:53
【问题描述】:

我需要将 xml 转换为数组:

XML

?xml version="1.0" standalone="yes"?>
<DocumentElement>
  <article>
    <a>TEST></a>
    <b>TEST2</b>
    <c>TEST3</c>
  </article>

  <article>
    <a>TEST4></a>
    <b>TEST5</b>
    <c>TEST6</c>
  </article>
</DocumentElement>

我需要一个这样的数组:

$testArray = array(
        array('a' => TEST, 'b' => 'TEST2', 'c' => TEST3),
        array('a' => TEST4, 'b' => 'TEST5', 'c' => TEST6)
    );

我的第一次尝试是:

$file = "product.xml";
$productArray = @simplexml_load_file($file) or
die ("ERROR loading file");

但是用那个方法我得到一个数组。

关于如何做到这一点的任何建议?

【问题讨论】:

    标签: php arrays xml


    【解决方案1】:

    如果您的 XML 结构是动态的,您可以创建几个循环来提取值以及元素的名称,并将它们一个一个地添加到结果数组中。

    $file = "product.xml";
    $productArray = simplexml_load_file($file) or
         die ("ERROR loading file");
    $articles = [];
    foreach ( $productArray->article as $article )  {
        $newElement = [];
        foreach ( $article as $element )    {
            $newElement [ $element->getName() ] = (string)$element;
        }
        $articles[] = $newElement;
    }
    
    print_r($articles);
    

    给...

    Array
    (
        [0] => Array
            (
                [a] => TEST>
                [b] => TEST2
                [c] => TEST3
            )
    
        [1] => Array
            (
                [a] => TEST4>
                [b] => TEST5
                [c] => TEST6
            )
    
    )
    

    【讨论】:

    【解决方案2】:

    当你这样做时

    $productArray = @simplexml_load_file($file) or die ("ERROR loading file");
    

    你会得到一个对象。

    如果你想循环浏览每篇文章,你可以这样做

    foreach($productArray ->children() as $article) { 
        echo $article->a. ", "; 
        echo $article->b. ", "; 
        echo $article->c. ", ";
    } 
    

    【讨论】:

      【解决方案3】:

      下面的代码通过您问题的 XML。

      <?PHP
      $link = 'yourxmlfile.xml'; //XML link
      $xml = simplexml_load_file($link); //load xml
      
      
      //Loop
      foreach($xml -> article as $item){ 
          echo "<strong>A:</strong> ".utf8_decode($item ->a)."<br />";
          echo "<strong>B:</strong> ".utf8_decode($item ->b)."<br />";
          echo "<strong>C:</strong> ".utf8_decode($item ->c)."<br />";
          echo "<br />";
      }
      

      【讨论】:

        猜你喜欢
        • 2012-08-22
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        相关资源
        最近更新 更多