我研究了一個答案,主要是在這個問題的答案Convert Tab delimited text file to XML的幫助下,將以下腳本拼湊在一起,逐行讀取CSV文件,然後將結果轉換爲XML文件。使用PHP將CSV文件轉換爲XML
CSV文件以這種方式有三個或更多細胞系:
李四[email protected] 2012/06/07 01:45
當互動PHP外殼跑時,下面的腳本忽略該文件的第一行,並吐出了一切,從兩行的時候,第一個XML標籤中:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$xmlWriter = new XMLWriter();
$xmlWriter->openUri('/path/to/destination.xml');
$xmlWriter->setIndent(true);
$xmlWriter->startDocument('1.0', 'UTF-8');
$xmlWriter->startElement('root');
$tsvFile = new SplFileObject('/path/to/destination.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
foreach ($tsvFile as $line => $row) {
if($line > 0 && $line !== ' ') {
$xmlWriter->startElement('item');
$xmlWriter->writeElement('name', $row[0]);
$xmlWriter->writeElement('email', $row[1]);
$xmlWriter->writeElement('date', $row[2]);
$xmlWriter->endElement();
}
}
$xmlWriter->endElement();
$xmlWriter->endDocument(); ?>
要解決這一點,我想這裏的解決方案:tab-delimited string to XML with PHP
下面是修改後的腳本:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$xmlWriter = new XMLWriter();
$xmlWriter->openUri('/path/to/destination.xml');
$xmlWriter->setIndent(true);
$xmlWriter->startDocument('1.0', 'UTF-8');
$xmlWriter->startElement('root');
$tsvFile = new SplFileObject('/path/to/destination.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$lines = explode("\n", $tsvFile);
$tsvData = array();
foreach ($lines as $line) {
if($line > 0) {
$tsvData[] = str_getcsv($line, "\t");
$tsvData[] = str_getcsv($line, "\t");
foreach ($tsvData as $row) {
$xmlWriter->writeElement('name', $row[0]);
$xmlWriter->writeElement('email', $row[1]);
$xmlWriter->writeElement('date', $row[2]);
$xmlWriter->endElement();
}
}
}
$xmlWriter->endElement();
$xmlWriter->endDocument();?>
此腳本創建的XML文件,但不幸的是產生它裏面沒有輸出。
有人能幫我指出我要去哪裏嗎?我不是這方面的專家,但是盡我最大的努力學習。
非常感謝您的幫助!
感謝你們,我正在取得一些進展:我意識到我應該保存我的文件作爲製表符分隔一個文件,這是它的原始格式。現在第二個腳本輸出:<?xml version =「1.0」encoding =「UTF-8」?>
Noak
2012-07-06 15:15:10