首頁 > 後端開發 > php教程 > PHP xml to csv

PHP xml to csv

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2016-06-23 14:36:30
原創
1037 人瀏覽過

From: 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:

<?$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
相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
用php合併格式一樣的csv
來自於 1970-01-01 08:00:00
0
0
0
反轉PHP讀取CSV文件
來自於 1970-01-01 08:00:00
0
0
0
nginx - linux+nignx伺服器上,php無法讀寫xml
來自於 1970-01-01 08:00:00
0
0
0
使用 PHP 表單中的資料更新 xml 命名空間
來自於 1970-01-01 08:00:00
0
0
0
Translate PHP腳本以讀取CSV檔案並傳回echo多次
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板