在PHP中将XML转换为CSV [英] XML to CSV in PHP

查看:100
本文介绍了在PHP中将XML转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码将XML转换为CSV,但仅在只有一行的情况下它将起作用.多个条目将仅显示标题/列名称.

I am trying to convert XML to CSV with the code below but it will only work if there is only one row. Multiple entries will only display the headers/column names.

这是我的XML的样子:

This is what my XML looks like:

<Cars>
  <Type>B</Type>
  <Car>
    <Brand>Car1</Brand>
    <Model>M1</Model>
    <Year>2010</Year>
    <Age>9</Age>
    <Desciption>test</Desciption>
  </Car>
</Cars>


<Cars>
  <Type>B</Type>
  <Car>
    <Brand>Car2</Brand>
    <Model>M2</Model>
    <Year>2015</Year>
    <Age>4</Age>
    <Desciption>test</Desciption>
  </Car>
</Cars>

我的代码:

 $filexml='cars.xml';

  $cname=array();

  $cname[] = 'Brand';
  $cname[] = 'Model';
  $cname[] = 'Year';
  $cname[] = 'Age';
  $cname[] = 'Desciption';


  if (file_exists($filexml)) {
      $xml = simplexml_load_file($filexml); 
      $f = fopen('cars.csv', 'w') or die('Can\'t create .csv file, try again later.');
      fputcsv($f, $cname);

      foreach ($xml->Car as $Car) {
        fputcsv($f, get_object_vars($Car),',','"');
      } 

      fclose($f);

  }

推荐答案

假设您的XML实际上是有效的(具有单个根元素),那么该结构的简化视图是这样的:

Assuming that your XML is actually valid (has a single root element) then a simplified view of the structure is this:

<document>
    <Cars>
       <Car>
          <Brand>Car1</Brand>
       </Car>
    </Cars>
    <Cars>
       <Car>
          <Brand>Car2</Brand>
       </Car>
    </Cars>
</document>

请注意,同一级别上有多个Cars节点,但每个节点中只有一个Car.

Note that there are multiple Cars nodes at the same level, but only one Car in each one.

加载XML时,初始PHP变量将表示<document>元素.

When you load the XML, your initial PHP variable will represent the <document> element.

因此您可以像这样手动访问前两个品牌((string)从XML元素获取文本内容):

So you could access the first two brands by hand like this (the (string) gets the text content from the XML element):

  • (string)$xml->Cars[0]->Car->Brand
  • (string)$xml->Cars[1]->Car->Brand
  • (string)$xml->Cars[0]->Car->Brand
  • (string)$xml->Cars[1]->Car->Brand

要获得所有品牌,您需要遍历$xml->Cars:

To get all the brands, you need to loop over $xml->Cars:

foreach ( $xml->Cars as $CarsNode ) {
   $CarNode = $CarsNode->Car;
   $brand = (string)$CarNode->Brand;
}

从那里,您可以使用现有代码在CSV文件中写一行.

From there, you can use your existing code to write a row to your CSV file.

这篇关于在PHP中将XML转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆