2017-10-28 11 views
1

私はCSVファイルをXMLに変換しようとしています。私はポストから得た以下のスクリプトを使用しています。しかし、それは私の側で働いていない。なぜ私はこのエラーが表示されますか?PHPスクリプトを使用してCSVファイルをXMLに変換するにはどうすればよいですか?

error_reporting(E_ALL | E_STRICT); 
ini_set('display_errors', true); 
ini_set('auto_detect_line_endings', true); 

$inputFilename = 'test.csv'; 
$outputFilename = 'test.xml'; 

// Open csv to read 
$inputFile = fopen($inputFilename, 'rt'); 

// Get the headers of the file 
$headers = fgetcsv($inputFile); 

// Create a new dom document with pretty formatting 
$doc = new DomDocument(); 
$doc->formatOutput = true; 

// Add a root node to the document 
$root = $doc->createElement('rows'); 
$root = $doc->appendChild($root); 

// Loop through each row creating a <row> node with the correct data 
while (($row = fgetcsv($inputFile)) !== FALSE) 
{ 
    $container = $doc->createElement('row'); 
    foreach($headers as $i => $header) 
    { 
     $child = $doc->createElement($header); 
     $child = $container->appendChild($child); 
     $value = $doc->createTextNode($row[$i]); 
     $value = $child->appendChild($value); 
    } 

    $root->appendChild($container); 
} 

$strxml = $doc->saveXML(); 

私は取得していますエラーはここにある:ここで

Uncaught exception 'DOMException' with message 'Invalid Character Error' 

は私のcsvファイルである:あなたのヘッダー行にフィールド名の周りのスペースを持っている

name, email, test 
    john,[email protected],blah 
    mary,[email protected],something 
    jane,[email protected],blarg 
    bob,[email protected],asdfsfd 
+0

https://stackoverflow.com/questions/4852796/php-script-to-convert-csv-files-to-xml – MikeyBunny

+0

@MikeyBunnyはい、私はその投稿に続く。しかし、それは私の側で働いていない。 – Cristal

+0

最初の数行でもCSVファイルを含めることができますか? –

答えて

0

、スペースが座っていませんXML要素の名前とよく似ています。単純)(トリムフィールド名...

$child = $doc->createElement(trim($header)); 
関連する問題