php
  • json
  • csv
  • 2017-03-14 2 views 1 likes 
    1

    안녕하세요, 저는 json을 csv로 변환하는 데 작은 문제가 있습니다. 나는이 [{"name":"Wayne","age":28},{"name":"John","age":21},{"name":"Sara","age":24}]하고 작업을 완벽하게 같은 다른 JSON 형식으로 시도json을 csv로 PHP를 사용하여 변환

    $jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}'; 
    
    //Decode the JSON and convert it into an associative array. 
    $jsonDecoded = json_decode($jsonString, true); 
    
    //Give our CSV file a name. 
    $csvFileName = 'file.csv'; 
    
    //Open file pointer. 
    $fp = fopen($csvFileName, 'w'); 
    
    //Loop through the associative array. 
    foreach($jsonDecoded as $row){ 
        //Write the row to the CSV file. 
        fputcsv($fp, $row); 
    } 
    
    //Finally, close the file pointer. 
    fclose($fp); 
    
    ?> 
    

    : 다음은 내 코드입니다. 내 코드를 수정하여 csv 형식으로 올바르게 저장하는 방법.

    사진 : 이 지금은 같은 저장 : pic 1이 같은 저장해야 : pic 2

    누군가가 나를 도울 수 있습니까? 이 작동

    +0

    사용이 https://github.com/danmandle/JSON2CSV –

    +1

    이해 귀하의 데이터 구조 즉'$ jsonDecoded' 배열 그리고 당신이 뭘 잘못하고 있는지 볼 수 – RiggsFolly

    답변

    1

    희망 ..

    <?php 
    
    $jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}'; 
    
    $jsonDecoded = json_decode($jsonString, true); 
    $csvHeader=array(); 
    $csvData=array(); 
    jsontocsv($jsonDecoded); 
    print_r($csvHeader); 
    print_r($csvData); 
    
    
    
    $csvFileName = 'file.csv'; 
    $fp = fopen($csvFileName, 'w'); 
    fputcsv($fp, $csvHeader); 
    fputcsv($fp, $csvData); 
    fclose($fp); 
    
    function jsontocsv($data) 
    { 
        global $csvData,$csvHeader; 
        foreach($data as $key => $value) 
        { 
         if(!is_array($value)) 
         { 
          $csvData[]=$value; 
          $csvHeader[]=$key; 
         } 
         else 
         { 
          jsontocsv($value); 
         } 
        } 
    } 
    

    JSON이

    <?php 
    
    $jsonString =file_get_contents("http://samples.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&appid=b1b15e88fa797225412429c1c50c122a1");; 
    $jsonDecoded = json_decode($jsonString, true); 
    $csvHeader=array(); 
    $csvData=array(); 
    $csvFileName = 'file.csv'; 
    $fp = fopen($csvFileName, 'w'); 
    $counter=0; 
    foreach($jsonDecoded["list"] as $key => $value) 
    { 
        jsontocsv($value); 
        if($counter==0) 
        { 
         fputcsv($fp, $csvHeader); 
         $counter++; 
        } 
        fputcsv($fp, $csvData); 
        $csvData=array(); 
    } 
    fclose($fp); 
    
    function jsontocsv($data) 
    { 
        global $csvData,$csvHeader; 
        foreach($data as $key => $value) 
        { 
         if(!is_array($value)) 
         { 
          $csvData[]=$value; 
          $csvHeader[]=$key; 
         } 
         else 
         { 
          jsontocsv($value); 
         } 
        } 
    } 
    
    +0

    제발 게시물을 해달라고 swer off-site. 그들은 어떻게 미래의 방문자들에게 어떤 용도로 사용될 것입니까? – RiggsFolly

    +0

    이것은 완벽하게 작동합니다 감사합니다! 하지만 json을 다음과 같이 사용하면 왜 작동하지 않습니다 : http://samples.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&appid=b1b15e88fa797225412429c1c50c122a1 –

    +0

    @GeorgiBangeev 그 질문에 따라 대답하지만 당신이 참조하는 json은이 코드를 통해 수행 할 수없는 여러 행과 중첩 된 데이터를 포함합니다. 나는 그 특정 json에 대한 내 게시물을 업데이 트하고 있습니다. –

    0

    이 시도 :

    $rowNr = 0; 
    $prevKey = ""; 
    $target = []; 
    
    $iterator = new RecursiveArrayIterator($jsonDecoded['list'][$rowNr]); 
    iterator_apply($iterator, 'traverseStructure', array($iterator,$prevKey,&$target)); 
    
    function traverseStructure($iterator, $prevKey, &$target) { 
    
    while ($iterator -> valid()) { 
        if ($iterator -> hasChildren()) {   
         $prevKey = $iterator->key(); 
         traverseStructure($iterator -> getChildren(), $prevKey, $target);    
        } 
        else {      
         if(isset($prevKey) && !is_int($prevKey)){    
          $row1 = $prevKey."/".$iterator->key();    
         }else{ 
          $row1 = $iterator->key(); 
         }   
         $row2 = $iterator->current();   
         $target[$row1] = $row2;   
        } 
        $iterator -> next();   
        } 
    } 
    
    fputcsv($fp, array_keys($target)); 
    fputcsv($fp, array_values($target)); 
    
    관련 문제