Home > Backend Development > PHP Tutorial > php function str_getcsv() that parses CSV strings into arrays

php function str_getcsv() that parses CSV strings into arrays

黄舟
Release: 2023-03-16 22:56:01
Original
1891 people have browsed it

定义和用法

str_getcsv() 函数解析 CSV 格式字段的字符串,并返回一个包含所读取字段的数组

语法

str_getcsv(string,separator,enclosure,escape)
Copy after login
参数描述
string必需。规定要解析的字符串。
separator可选。设置字段分界符(只允许一个字符),默认值为逗号( , )。
enclosure可选。设置字段环绕符(只允许一个字符),默认值为双引号( " )。
escape可选。设置转义字符(只允许一个字符),默认值为反斜线( \ )。

技术细节

返回值:以数组形式返回 CSV 字段。
PHP 版本:5.3.0+

php提供了str_getcsv方法,可以把字符串作为csv格式来处理,这样方便解析为数组。

str_getcsv 解析csv字符串为数组

array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
Copy after login

参数:
input 待解析的字符串
delimiter 设定字段界定符(仅单个字符)
enclosure 设定字段包裹字符(仅单个字符)
escape 设置转义字符(仅单个字符),默认为反斜线(\)

实例:

<?php$str = "中国,广东省,广州市,天河区,&#39;113.329884,23.154799&#39;,1,&#39;2016-01-01 12:00:00&#39;,&#39;1,2,3,4,5,6&#39;";
$arr = str_getcsv($str, &#39;,&#39;, "&#39;");
print_r($arr);
?>
Copy after login

输出:

Array(
    [0] => 中国
    [1] => 广东省
    [2] => 广州市
    [3] => 天河区
    [4] => 113.329884,23.154799
    [5] => 1
    [6] => 2016-01-01 12:00:00
    [7] => 1,2,3,4,5,6)
Copy after login


The above is the detailed content of php function str_getcsv() that parses CSV strings into arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template