Write a CSV file from a PHP Array

前端 未结 3 2109
走了就别回头了
走了就别回头了 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:55

    Try below solution header of csv will be (item, cost, approved by) - replace $data with your array variable:

    $data = array(
        array( 'item' => 'Server', 'cost' => 10000, 'approved by' => 'Joe'),
        array( 'item' => 'Mt Dew', 'cost' => 1.25, 'approved by' => 'John'),
        array( 'item' => 'IntelliJ IDEA', 'cost' => 500, 'approved by' => 'James')
    );
    
    $fp = fopen('file.csv', 'w');
    $i = 0;
    foreach ($data as $fields) {
        if($i == 0){
            fputcsv($fp, array_keys($fields));
        }
        fputcsv($fp, array_values($fields));
        $i++;
    }
    
    fclose($fp);
    

    for more detail have alook at : PHP: fputcsv - Manual

提交回复
热议问题