Convert XML to CSV in PHP

给你一囗甜甜゛ 提交于 2021-02-04 12:43:06

问题


Is there a way to convert an XML file to a CSV using PHP?


回答1:


Use search engines to locate code samples such as http://codestips.com/php-xml-to-csv/

To create a csv file from a xml in PHP 5.0 it’s very simple, we will just have to write some lines.

We will use the SimpleXML extension that come from PHP 5.0.

SimpleXML reads an entire xml into an object that we can iterate through his properties. To write to the csv output file we will use fputcsv.

fputcsv formats a line as csv and writes it to the file.

Suppose we are having this xml named cars.xml:

<?xml version='1.0'?>
<cars>
<car>
 <color>blue</color>
 <price>2000</price>
</car>
<car>
 <color>red</color>
 <price>10000</price>
</car> 
<car>
 <color>black</color>
 <price>5000</price>
</car>
</cars>

First we should read our xml using simplexml_load_file passing the name of the file and returns an object with all the properties and values of the csv:

$xml = simplexml_load_file($filexml);

After reading it we should iterate through all the child nodes of cars and write it to the output file using fputcsv specifying the object,delimiter and enclosure. We should first convert the object into an array in order to write it to the csv:

foreach ($xml->car as $car) 
fputcsv($f, get_object_vars($car),',','"');

Here is the complete source code that converts xml to csv in php 5.0:

<?php
$filexml='cars.xml';
if (file_exists($filexml)) {
    $xml = simplexml_load_file($filexml);
$f = fopen('cars.csv', 'w');
foreach ($xml->car as $car) {
    fputcsv($f, get_object_vars($car),',','"');
}
fclose($f);
}
?>



回答2:


Here is a very good code example. working fine with my rquirement.

<?php
$headers = array();
foreach ($xml->ROW->children() as $field) {
    $headers[] = $field->getName();
}
$filename = '';
$csv_filename = str_replace('xml', 'csv', $filename);
$file = $this->getCsvDirectory() . '/' . $csv_filename;

$csv = fopen($file, 'w');
fputcsv($csv, $headers, ',', '"');
foreach ($xml as $entry) {
    $data = get_object_vars($entry);
    $sanitized_data = array();
    foreach ($data as $key => $datum) {
        $sanitized_data[$key] = html_entity_decode($datum, ENT_COMPAT, 'UTF-8');
    }
    fputcsv($csv, $sanitized_data, ',', '"');
}
fclose($csv);
?>


来源:https://stackoverflow.com/questions/2126510/convert-xml-to-csv-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!