1

XMLを取得してCSVに変換する簡単な小さなスクリプトがあります。ただし、ヘッダーは書き込まれません。ヘッダーの書き方を知っている人はいますか?

$file='example.xml';
if (file_exists($file)) {
    $xml = simplexml_load_file($file);
    $f = fopen('newfile.csv', 'w');
    foreach ($xml->Information as $information) {
        fputcsv($f, get_object_vars($information),',','"');
    }
    fclose($f);
}

これにより、の子要素のすべてのコンテンツが<Information>Excelの適切な列に配置されます。ただし、要素名はCSV見出しとして書き込まれません。

スクリプトを編集してヘッダーも含める方法はありますか?

ありがとう

マイク

4

1 に答える 1

2

SimpleXMLElement :: getName()関数を使用して、最初のデータセットから要素名を取得し、それを使用してCSVヘッダーを書き込むことができます。

$file='example.xml';
if (file_exists($file)) {
    $xml = simplexml_load_file($file);
    $f = fopen('newfile.csv', 'w');

    // array to hold the field names
    $headers = array(); 
    // loop through the first set of fields to get names
    foreach ($xml->Information->children() as $field) { 
        // put the field name into array
        $headers[] = $field->getName(); 
    }
    // print headers to CSV
    fputcsv($f, $headers, ',', '"');

    foreach ($xml->Information as $information) {
        fputcsv($f, get_object_vars($information), ',', '"');
    }
    fclose($f);
}
于 2012-10-14T01:48:18.143 に答える