PHP CSV字符串到数组

2020/11/30 20:21 · php ·  · 0评论

我正在尝试将CS​​V字符串解析为PHP中的数组。CSV字符串具有以下属性:

Delimiter: ,
Enclosure: "
New line: \r\n

示例内容:

"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"

当我尝试这样解析时:

$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);

最后一个元素和第一个元素串联在一个字符串中:

[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""

我怎样才能解决这个问题?任何帮助,将不胜感激。

做这个:

$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}
print_r($array);

它会给你这样的输出:

Array
(
    [0] => Array
        (
            [0] => 12345
            [1] => Computers
            [2] => Acer
            [3] => 4
            [4] => Varta
            [5] => 5.93
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

    [1] => Array
        (
            [0] => 12346
            [1] => Computers
            [2] => Acer
            [3] => 5
            [4] => Decra
            [5] => 5.94
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

)

我希望这可以有所帮助。

您应该使用fgetcsv。 由于csv是变量,因此无法将文件作为流导入,因此您应该使用php://tempphp://memory首先将字符串欺骗为文件

$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);

然后,使用fgetcsv将没有问题:

$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
    $csv[] = $data;
}

$data 将会是单个csv行的数组(可能包括换行符或逗号等)。

方便的内衬:

$csv = array_map('str_getcsv', file('data.csv'));

我已经使用以下函数将csv字符串解析为关联数组

public function csvToArray($file) {
    $rows = array();
    $headers = array();
    if (file_exists($file) && is_readable($file)) {
        $handle = fopen($file, 'r');
        while (!feof($handle)) {
            $row = fgetcsv($handle, 10240, ',', '"');
            if (empty($headers))
                $headers = $row;
            else if (is_array($row)) {
                array_splice($row, count($headers));
                $rows[] = array_combine($headers, $row);
            }
        }
        fclose($handle);
    } else {
        throw new Exception($file . ' doesn`t exist or is not readable.');
    }
    return $rows;
}

如果您的csv文件名为mycsv.csv,则可以将此函数称为:

$dataArray = csvToArray(mycsv.csv);

您也可以在http://www.scriptville.in/parse-csv-data-to-array/中获得此脚本

使用修改以前的答案array_map

用多行炸毁CSV数据。

$csv = array_map('str_getcsv', explode("\n", $csvData));

版本略短,没有不必要的第二个变量:

$csv = <<<'ENDLIST'
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
ENDLIST;

$arr = explode("\n", $csv);
foreach ($arr as &$line) {
  $line = str_getcsv($line);
}

如果您需要csv列的名称,则可以使用此方法

 $example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));

如果列中有回车/换行符,则str_getcsv将不起作用。

尝试https://github.com/synappnz/php-csv

使用:

include "csv.php";
$csv = new csv(file_get_contents("filename.csv"));
$rows = $csv->rows();
foreach ($rows as $row)
{
  // do something with $row
}

您可以使用此功能将CSV字符串转换为Array。

    function csv2array(
        $csv_string,
        $delimiter = ",",
        $skip_empty_lines = true,
        $trim_fields = true,
        $FirstLineTitle = false
    ) {
        $arr = array_map(
            function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
                if ($FirstLineTitle && !$FirstLine) {
                    $FirstLine = explode( $delimiter, $result[0] );
                }
                $lineResult = array_map(
                    function ( $field ) {
                        return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
                    },
                    $trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
                );
                return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
            },
            ($result = preg_split(
                $skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
                preg_replace_callback(
                    '/"(.*?)"/s',
                    function ( $field ) {
                        return urlencode( utf8_encode( $field[1] ) );
                    },
                    $enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
                )
            ))
        );
        return $FirstLineTitle ? array_splice($arr, 1) : $arr;
    }

试试这个,对我有用:

$delimiter = ",";
  $enclosure = '"';
  $escape = "\\" ;
  $rows = array_filter(explode(PHP_EOL, $content));
  $header = NULL;
  $data = [];

  foreach($rows as $row)
  {
    $row = str_getcsv ($row, $delimiter, $enclosure , $escape);

    if(!$header) {
      $header = $row;
    } else {
      $data[] = array_combine($header, $row);
    }
  }
本文地址:http://php.askforanswer.com/php-csvzifuchuandaoshuzu.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!