2017-11-13 15 views
2

こんにちは私はcssファイルに通常のものよりdifferrent配列構造を持つJSONファイルを変換しようとしています。私はそれをcsvファイルに変換する解決策を見つけようとしていましたが、解決策を見つけることはできません。どのようにJsonをCSVにPHPで変換する

<?php 
    $jsondata = '[{ 
     "accession_number_original": "2012.11.45", 
     "author_birth_date": [ 
      "1932" 
     ], 
     "author_date": [ 
      "1932" 
     ], 
     "author_death_date": [ 
      "" 
     ], 
     "author_description": [ 
      "American" 
     ], 
     "author_display": [ 
      "Day yon" 
     ], 
     "author_names_first": [ 
      "Day" 
     ], 
     "author_names_last": [ 
      "yon" 
     ], 
     "author_names_middle": [ 
      "" 
     ], 
     "image_height": "12 1/2", 
     "image_width": "18 1/4", 
     "jp2_image_url": "", 
     "location_physical_location": "Art Gallery", 
     "location_shelf_locator": "Unknown", 
     "master_image_url": "", 
     "note_provenance": "Gift of Gary Ginsberg and Susanna Aaron", 
     "object_date": "1963/2010", 
     "object_depth": "", 
     "object_height": "", 
     "object_width": "", 
     "origin_datecreated_end": "1963", 
     "origin_datecreated_start": "1963", 
     "physical_description_extent": [ 
      "12 1/2 x 18 1/4" 
     ], 
     "physical_description_material": [ 
      "Gelatin silver print" 
     ], 
     "physical_description_technique": [ 
      "Gelatin silver print" 
     ], 
     "pid": "bdr:123456", 
     "title": "As Demonstrators" 
     }]'; 

    $jsonDecoded = json_decode($jsondata); 
    print_r('<pre>'); 
    print_r($jsonDecoded); 
    print_r('</pre>'); 
    $fh = fopen('fileout.csv', 'w'); 
    if (is_array($jsonDecoded)){ 
     print_r('<-------- line variable output-------->'); 
     foreach($jsonDecoded as $line){ 
      print_r('<pre>'); print_r($line); print_r('</pre>'); 
     print_r('<-------- data variable output-------->'); 
     if (is_array($line)||is_object($line)){ 
      foreach($line as $data){ 
      fputcsv($fp,$data); 
      } 
      } 
     } 
     } 
    } 

    fclose($fh); 
    print_r('Converted Successfully'); 
?> 

私はstackoverflowで同様の質問のほとんどを調べてみましたが、どれも私の種類の配列を持っていないので、あまり役に立ちません。

私は、単一のforeachを使用している場合、私は文字列の変換にエラー配列を取得していますがアレイは、csvファイルに代わり、実際のデータの値として印刷されていませんでした。

私は2つのforeachを使用している場合は、私が(エラーfputcsvを取得していますが)、パラメータ2が

指定された配列の文字列であることを期待PHPExcelライブラリーに使用

Array 
(
[0] => stdClass Object 
    (
     [accession_number_original] => 2012.11.45 
     [author_birth_date] => Array 
      (
       [0] => 1932 
      ) 

     [author_date] => Array 
      (
       [0] => 1932 
      ) 

     [author_death_date] => Array 
      (
       [0] => 
      ) 

     [author_description] => Array 
      (
       [0] => American 
      ) 

     [author_display] => Array 
      (
       [0] => Day yon 
      ) 

     [author_names_first] => Array 
      (
       [0] => Day 
      ) 

     [author_names_last] => Array 
      (
       [0] => yon 
      ) 

     [author_names_middle] => Array 
      (
       [0] => 
      ) 

     [image_height] => 12 1/2 
     [image_width] => 18 1/4 
     [jp2_image_url] => 
     [location_physical_location] => Art Gallery 
     [location_shelf_locator] => Unknown 
     [master_image_url] => 
     [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron 
     [object_date] => 1963/2010 
     [object_depth] => 
     [object_height] => 
     [object_width] => 
     [origin_datecreated_end] => 1963 
     [origin_datecreated_start] => 1963 
     [physical_description_extent] => Array 
      (
       [0] => 12 1/2 x 18 1/4 
      ) 

     [physical_description_material] => Array 
      (
       [0] => Gelatin silver print 
      ) 

     [physical_description_technique] => Array 
      (
       [0] => Gelatin silver print 
      ) 

     [pid] => bdr:123456 
     [title] => As Demonstrators 
    ) 
) 
+0

(文字列にauthor_ *を変換する)最初の段階で配列を取り除くと、それが文字列に配列をスローしません。エラー – moped

+0

@ mopedコメントありがとうございます、少し詳細を与えることができますか?私は手動でキー値なしですべての配列を変換するか、それを行う方法があります。私と一緒に私はちょうどPHPを学び始めた。 – miststudent2011

+0

私の答えをチェックし、何かが不明な場合はコメントに尋ねてください。 – moped

答えて

1

私はコメントで述べたように、最初のステップは、配列値の世話をすることですので、各行が値を持っている必要があり、配列がある場合(それだけで、あなたが提供する形式でカウント変換2つの値で、最初のものだけがcsvに渡されます)。

あなたの修正されたソースコード:実行後の

$jsonDecoded = json_decode($jsondata, true); // add true, will handle as associative array  
print_r('<pre>'); 
print_r($jsonDecoded); 
print_r('</pre>'); 
$fh = fopen('fileout.csv', 'w'); 
if (is_array($jsonDecoded)) { 
    print_r('<-------- line variable output-------->'); 
    foreach ($jsonDecoded as $line) { 
    // with this foreach, if value is array, replace it with first array value 
    foreach ($line as $key => $value) { 
     if (is_array($value)) { 
      $line[$key] = $value[0]; 
     } 
    } 
    print_r('<pre>'); print_r($line); print_r('</pre>'); 
    // no need for foreach, as fputcsv expects array, which we already have 
    if (is_array($line)) { 
     fputcsv($fh,$line); 
    } 
    } 
} 
fclose($fh); 
print_r('Converted Successfully'); 

スクリプトの出力:

[output of your print_r($jsonDecoded);] 

<-------- line variable output--------> 

Array 
(
    [accession_number_original] => 2012.11.45 
    [author_birth_date] => 1932 
    [author_date] => 1932 
    [author_death_date] => 
    [author_description] => American 
    [author_display] => Day yon 
    [author_names_first] => Day 
    [author_names_last] => yon 
    [author_names_middle] => 
    [image_height] => 12 1/2 
    [image_width] => 18 1/4 
    [jp2_image_url] => 
    [location_physical_location] => Art Gallery 
    [location_shelf_locator] => Unknown 
    [master_image_url] => 
    [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron 
    [object_date] => 1963/2010 
    [object_depth] => 
    [object_height] => 
    [object_width] => 
    [origin_datecreated_end] => 1963 
    [origin_datecreated_start] => 1963 
    [physical_description_extent] => 12 1/2 x 18 1/4 
    [physical_description_material] => Gelatin silver print 
    [physical_description_technique] => Gelatin silver print 
    [pid] => bdr:123456 
    [title] => As Demonstrators 
) 

Converted Successfully 
+0

ソリューションのためにありがとうが何もCSVファイルに書き込まれていません私はファイルを書き込むための許可を持っていた空のファイルが作成されているだけでなく、print_r( '

'); print_r($line); print_r('
' );出力を提供しません。 – miststudent2011

+0

は私の開発者でうまくいきますので、あなたのソースだと思うので、jsonの文字列の後にこの部分だけをコピー/貼り付けて、もう一度ファイルをチェックしてください。 – moped

+0

あなたのソースコードと必要な修正がすべて含まれるように私の答えを編集しました。あなたの '$ jsondata'をファイルの上に入れてください。 – moped

0

を次のようにのvar_dumpや復号化されたJSONのしますprint_r結果がありますそれは私のjsonファイルをExcelシートに変換するのに役立ちます。 https://github.com/PHPOffice/PHPExcel

   $keyName=array(); 
       $i=0; 
       $current_data=file_get_contents($dir.$excelFileLocation,true); 
       $excelFile=fopen($dir."ExcelTojson.xls","w+"); 
       $array_data=json_decode($current_data,true); 
       foreach($array_data as $jsonValue) 
       { 
        foreach($jsonValue as $key => $value) 
        { 
         if($i==0) 
         { 
          $keyName[$i]=$key; 
          $i++; 
         } 
         else 
         { 
          $check=0; 
          for($j=0;$j<count($keyName);$j++) 
          { 
           if($keyName[$j]==$key) 
           { 
            $check=1; 
            break; 
           } 
          } 
          if($check==0) 
          { 
           $keyName[$i]=$key; 
           $i++; 
          } 
         } 
        } 
       } 
       $excelSheet = PHPExcel_IOFactory::load($dir."ExcelTojson.xls"); 
       $excelSheet->setActiveSheetIndex(0); 
       $ascii=65; 
       for($i=0;$i<count($keyName);$i++) 
       { 
        $excelSheet->getActiveSheet()->setCellValue(chr($ascii)."1",stripslashes($keyName[$i])); 
        $ascii+=1; 
       } 
       $cellValue=2; 
       foreach($array_data as $jsonValue) 
       { 
        $ascii=65; 
        foreach($jsonValue as $key => $value) 
        { 
         $excelSheet->getActiveSheet()->setCellValue(chr($ascii).$cellValue,stripslashes($value)); 
         $ascii+=1; 
        } 
        $cellValue+=1; 
       } 

       $filename="ExcelTojson.xls"; 
       header('Content-Type: application/vnd.ms-excel'); 
       header('Content-Disposition: attachment;filename="'.$filename.'"'); 
       header('Cache-Control: max-age=0'); 
       $objWriter = PHPExcel_IOFactory::createWriter($excelSheet, 'Excel5'); 
       $objWriter->save('php://output'); 
+0

回答ありがとうございますが、readmeによると、jsonを読むことはできません。何か不足しているのですか、より具体的な情報が必要ですか? – miststudent2011

+0

jsonデコードを使用してur jsonを読み込んで、同じインデックスの配列に配列キーと値を格納します。\t \t \t $ excelSheet = PHPExcel_IOFactory :: load($ dir。 "ExcelTojson.xls"); \t \t \t \t \t $ excelSheet-> setActiveSheetIndex(0); \t \t \t \t $ ascii = 65; (; $ iは$ i = 0 \t \t \t \t \t <カウント($キー名); $ iは++) \t \t \t \t \t { \t \t \t \t \t \t $ excelSheet-> GetActiveSheet関数() - > setCellValue( chr($ ascii)。"1"、stripslashes($ keyName [$ i])); \t \t \t \t \t \t $ ascii + = 1; \t \t \t \t \t} –

+1

これはあなたがあなたの答えを編集した可能性が+行き過ぎソリューションは、ソースコードがコメントに難読み取り可能なされます。) – moped

関連する問題