私は答えを調べ、主にこの質問Convert Tab delimited text file to XMLの答えの助けを借りて、次のスクリプトをつなぎ合わせて CSV ファイルを 1 行ずつ読み取り、結果を XML ファイルに変換しました。
CSV ファイルには、次のように 3 つ以上のセルを含む行があります。
ジョン・ドウ john_doe@email.com 06/07/2012 01:45
次のスクリプトを Interactive PHP シェルで実行すると、ファイルの最初の行が無視され、最初の xml タグ内のすべてが一度に 2 行ずつ出力されます。
<?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(); ?>
これを解決するために、ここで解決策を試しました:タブ区切りの文字列を 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");
$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 ファイルを作成しますが、残念ながらその中に出力を生成しません。
誰かが私が間違っている場所を指摘することで私を助けることができますか? 私はこれの専門家ではありませんが、一生懸命勉強しようとしています。
あなたの助けは大歓迎です!