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:
blue 2000 red 10000 black 5000
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:
$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);}?>Download php source code for converting xml into a csv
推荐阅读
-
Android实现波浪线效果(xml bitmap)
-
PHP中number_format()函数的用法讲解
-
jquery+php后台实现省市区联动功能示例
-
PHP中str_split()函数的用法讲解
-
PHP简单实现文本计数器的方法
-
抛弃 PHP 代价太高
-
工作中常用的mysql语句分享 不用php也可以实现的效果
-
PHP抓取及分析网页的方法详解
-
Laravel访问出错提示:`Warning: require(/vendor/autoload.php): failed to open stream: No such file or di解决方法
-
PHP调用存储过程返回值不一致问题的解决方法分析