Home >Backend Development >PHP Tutorial >How can I convert an array into a CSV file in PHP?
Convert Array into CSV: A Comprehensive Guide
CSV (Comma-Separated Values) is a widely used format for storing tabular data. Converting an array into a CSV file allows for easy data transfer and analysis. This article provides a step-by-step guide on how to accomplish this conversion.
The Array
Consider the following stdClass Object array:
stdClass Object ( [OrderList_RetrieveByContactResult] => stdClass Object ( [OrderDetails] => stdClass Object ( [entityId] => 1025298 [orderId] => 10952 [... various properties ...] ) ) )
Conversion Function
To convert the array into CSV, we can use a helper function that encapsulates the logic. Here's an example function:
/** * Formats a line (passed as a fields array) as CSV and returns the CSV as a string. * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120 */ function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) { $delimiter_esc = preg_quote($delimiter, '/'); $enclosure_esc = preg_quote($enclosure, '/'); $output = array(); foreach ( $fields as $field ) { if ($field === null && $nullToMysqlNull) { $output[] = 'NULL'; continue; } // Enclose fields containing $delimiter, $enclosure or whitespace if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) { $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure; } else { $output[] = $field; } } return implode( $delimiter, $output ); }
This function takes an array, delimiter, and enclosure characters as inputs. It processes each field in the array, enclosing fields that contain special characters. Finally, it formats the fields as a CSV string and returns it.
Applying the Conversion
To convert our sample array, we can call the arrayToCsv function:
$fields = [$array->OrderList_RetrieveByContactResult->OrderDetails]; $csv = arrayToCsv($fields);
The $csv variable now contains the converted CSV data. You can save it to a file or use it for further processing.
The above is the detailed content of How can I convert an array into a CSV file in PHP?. For more information, please follow other related articles on the PHP Chinese website!