Преобразование php-массива в строку csv
У меня есть несколько способов преобразования php-массива в строку csv как из stackoverflow, так и из google. Но у меня проблемы, если я хочу сохранить номер мобильного телефона, такой как 01727499452, он сохраняет как без первого значения 0.
В настоящее время я использую этот фрагмент кода:
Преобразование массива в csv
Кто-нибудь может помочь мне.
Array
[1] => Array
(
[0] => Lalu ' " ; \\ Kumar
[1] => Mondal
[2] => 01934298345
[3] =>
)
[2] => Array
(
[0] => Pritom
[1] => Kumar Mondal
[2] => 01727499452
[3] => Bit Mascot
)
[3] => Array
(
[0] => Pritom
[1] => Kumar Mondal
[2] => 01711511149
[3] =>
)
[4] => Array
(
[0] => Raaz
[1] => Mukherzee
[2] => 01911224589
[3] => Khulna University 06
)
)
Мой кодовый блок:
function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$outputString = "";
foreach($fields as $tempFields) {
$output = array();
foreach ( $tempFields 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 ) ) {
$field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
$output[] = $field." ";
}
$outputString .= implode( $delimiter, $output )."\r\n";
}
return $outputString; }
Спасибо,
Pritom.
Ответы
Ответ 1
Вы можете использовать функцию str_putcsv
:
if(!function_exists('str_putcsv'))
{
function str_putcsv($input, $delimiter = ',', $enclosure = '"')
{
// Open a memory "file" for read/write...
$fp = fopen('php://temp', 'r+');
// ... write the $input array to the "file" using fputcsv()...
fputcsv($fp, $input, $delimiter, $enclosure);
// ... rewind the "file" so we can read what we just wrote...
rewind($fp);
// ... read the entire line into a variable...
$data = fread($fp, 1048576);
// ... close the "file"...
fclose($fp);
// ... and return the $data to the caller, with the trailing newline from fgets() removed.
return rtrim($data, "\n");
}
}
$csvString = '';
foreach ($list as $fields) {
$csvString .= str_putcsv($fields);
}
Подробнее об этом на GitHub, функции, созданной @johanmeiring.
Ответ 2
Это то, что вам нужно?
$out = "";
foreach($array as $arr) {
$out .= implode(",", $arr) . "\r\n";
}
Он проходит через ваш массив, создавая новую строку в каждом цикле, разделяя значения массива на ",".
Ответ 3
Вы уверены, что цифры фактически сохраняются без начального нуля? Вы посмотрели фактический результат CSV в текстовом редакторе?
Если вы только что открыли файл CSV в приложении для работы с электронными таблицами, скорее всего это электронная таблица, которая интерпретирует ваши телефонные номера в виде числовых значений и отбрасывает нули при их отображении. Обычно вы можете исправить это в электронной таблице, изменив параметры форматирования в этом конкретном столбце.
Ответ 4
Поскольку это CSV, а не что-то вроде JSON, все будет читаться как строка в любом случае, поэтому просто преобразуйте свой номер в строку с помощью:
-
(string)$variable
-
strval($variable)
(который я бы предпочел здесь)
- объединить с пустой строкой, например
$variable . ''
PHP gettype()
также будет вариантом. Вы можете вводить каждое поле в строку (даже если она уже одна), используя один из описанных методов или вы можете вызывать только поле с номером, после которого делает это:
if (gettype($field) == 'integer' || gettype($field) == 'double') {
$field = strval($field); // Change $field to string if it a numeric type
}
Здесь добавлен полный код с ним
function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$outputString = "";
foreach($fields as $tempFields) {
$output = array();
foreach ( $tempFields as $field ) {
// ADDITIONS BEGIN HERE
if (gettype($field) == 'integer' || gettype($field) == 'double') {
$field = strval($field); // Change $field to string if it a numeric type
}
// ADDITIONS END HERE
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
$output[] = $field." ";
}
$outputString .= implode( $delimiter, $output )."\r\n";
}
return $outputString;
}
Ответ 5
Я использую эту функцию для преобразования php-массива в csv. Он также работает для многомерного массива.
public function array_2_csv($array) {
$csv = array();
foreach ($array as $item=>$val) {
if (is_array($val)) {
$csv[] = $this->array_2_csv($val);
$csv[] = "\n";
} else {
$csv[] = $val;
}
}
return implode(';', $csv);
}
Ответ 6
Вышеприведенная функция не совсем правильная, потому что она рассматривает \n как элемент, а это не то, что нам нужно, поскольку каждая строка должна отделяться только \n. Таким образом, более эффективный код будет:
function array2csv($array, $delimiter = "\n") {
$csv = array();
foreach ($array as $item=>$val)
{
if (is_array($val))
{
$csv[] = $this->array2csv($val, ";");
}
else
{
$csv[] = $val;
}
}
return implode($delimiter, $csv);
}
Ответ 7
Вот решение немного более общего назначения. Я на самом деле искал способ сделать списки строк для массовых вставок SQL. Код будет выглядеть так:
foreach ($rows as $row) {
$string = toDelimitedString($row);
// Now append it to a file, add line break, whatever the need may be
}
И вот полезная функция, которую я добавил в свой takeit:
/**
* Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since
* the quote character is customisable and the escaping behaviour is the same for CSV and SQL.
*
* Tests:
* echo toDelimitedString([], ',', '\'', true) . "\n";
* echo toDelimitedString(['A'], ',', '\'', true) . "\n";
* echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n";
* echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n";
* echo toDelimitedString([], ',', '\'', true) . "\n";
* echo toDelimitedString(['A'], ',', '"', true) . "\n";
* echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n";
* echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n";
*
* Outputs:
* <Empty String>
* 'A'
* 'A','B'
* 'A','B''C'
* <Empty String>
* "A"
* "A","B"
* "A","B""C"
*
* @param array $array A one-dimensional array of string literals
* @param string $delimiter The character to separate string parts
* @param string $quoteChar The optional quote character to surround strings with
* @param bool $escape Flag to indicate whether instances of the quote character should be escaped
* @return string
*/
function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true)
{
// Escape the quote character, since it is somewhat expensive it can be suppressed
if ($escape && !empty($quoteChar)) {
$array = str_replace($quoteChar, $quoteChar . $quoteChar, $array);
}
// Put quotes and commas between all the values
$values = implode($array, $quoteChar . $delimiter . $quoteChar);
// Put first and last quote around the list, but only if it is not empty
if (strlen($values) > 0) {
$values = $quoteChar . $values . $quoteChar;
}
return $values;
}