Write a CSV file from a PHP Array

前端 未结 3 2106
走了就别回头了
走了就别回头了 2021-01-19 18:33

I appreciate there are already a lot of questions around this subject. But, as I\'m not a PHP developer, I\'m struggling to get anything to work for my specific object struc

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-19 18:52

    For writing a PHP array to a CSV file you should use the built in PHP function fputcsv:

    Edit:

    More specific example based on your data input:

    username = "Rein";
        $obj->answer = "Correct";
        $obj->awesomeness = 1000;
    
        $array_of_objects[] = $obj;
    }
    
    // Open a file to write to
    $fp = fopen('file.csv', 'wb');
    
    $i = 0;
    
    // Loop the array of objects
    foreach( $array_of_objects as $obj )
    {
        // Transform the current object to an array
        $fields = array();
    
        foreach ($obj as $k => $v)
        {
            $fields[ $k ] = $v;
        }
    
        if( $i === 0 )
        {
            fputcsv($fp, array_keys($fields) ); // First write the headers
        }
    
        fputcsv($fp, $fields); // Then write the fields
    
        $i++;
    }
    
    fclose($fp);
    

    Edit 2:

    Based on new information (you have a JSON string to start with), I'm added this example as a better way to write the data to a CSV file:

提交回复
热议问题