使用 PHP 将 CSV 转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28118101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert CSV to JSON using PHP
提问by iori
I am trying to convert CSV file to JSON using PHP.
我正在尝试使用 PHP 将 CSV 文件转换为 JSON。
Here is my code
这是我的代码
<?php
date_default_timezone_set('UTC');
$today = date("n_j"); // Today is 1/23/2015 -> $today = 1_23
$file_name = $today.'.CSV'; // My file name is 1_23.csv
$file_path = 'C:\Users\bheng\Desktop\qb\'.$file_name;
$file_handle = fopen($file_path, "r");
$result = array();
if ($file_handle !== FALSE) {
$column_headers = fgetcsv($file_handle);
foreach($column_headers as $header) {
$result[$header] = array();
}
while (($data = fgetcsv($file_handle)) !== FALSE) {
$i = 0;
foreach($result as &$column) {
$column[] = $data[$i++];
}
}
fclose($file_handle);
}
// print_r($result); // I see all data(s) except the header
$json = json_encode($result);
echo $json;
?>
print_r($result);
// I see all data(s)
print_r($result);
// 我看到所有数据
Then I json_encode($result);
and tried to display it, but nothing is displaying on the screen at all. All I see is the blank screen, and 0 error message.
然后我json_encode($result);
尝试显示它,但屏幕上根本没有显示任何内容。我看到的只是空白屏幕和 0 错误消息。
Am I doing anything wrong ? Can someone help me ?
我做错了什么吗?有人能帮我吗 ?
Added Result of
print_r($result);
添加的结果
print_r($result);
Array (
[Inventory] => Array (
[0] => bs-0468R(20ug)
[1] => bs-1338R(1ml)
[2] => bs-1557G(no bsa)
[3] => bs-3295R(no BSA)
[4] => bs-0730R-Cy5"
[5] => bs-3889R-PE-Cy7"
[6] => 11033R
[7] => 1554R-A647
[8] => 4667
[9] => ABIN731018
[10] => Anti-DBNL protein
.... more ....
回答by Whirlwind
Try like this:
像这样尝试:
$file="1_23.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json = json_encode($array);
print_r($json);
回答by Renjith V R
You can try this way too.
你也可以试试这个方法。
<?php
function csvtojson($file,$delimiter)
{
if (($handle = fopen($file, "r")) === false)
{
die("can't open the file.");
}
$csv_headers = fgetcsv($handle, 4000, $delimiter);
$csv_json = array();
while ($row = fgetcsv($handle, 4000, $delimiter))
{
$csv_json[] = array_combine($csv_headers, $row);
}
fclose($handle);
return json_encode($csv_json);
}
$jsonresult = csvtojson("./doc.csv", ",");
echo $jsonresult;
回答by Kevin Khew
data.csv
数据.csv
Game,Skill
Treasure Hunter,pilipala
Rocket Launcher,bibobibo
Rocket Engine,hehehohoho
游戏,技能
寻宝猎人,pilipala
火箭发射器,bibobibo
火箭发动机,呵呵呵呵呵呵
To convert with column name, this is how I do it.
要使用列名进行转换,我就是这样做的。
csv2json.php
csv2json.php
<?php
if (($handle = fopen("data.csv", "r")) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
$json = json_encode($datas);
fclose($handle);
print_r($json);
}
The output result
输出结果
[
{
"Game": "Treasure Hunter",
"Skill": "pilipala"
},
{
"Game": "Rocket Launcher",
"Skill": "bibobibo"
},
{
"Game": "Rocket Engine",
"Skill": "hehehohoho"
}
]
回答by Samwise
I ran into a similar problem, I ended up using this to recursively convert the data to UTF-8 on an array before encoding to JSON.
我遇到了类似的问题,我最终使用它在编码为 JSON 之前在数组上递归地将数据转换为 UTF-8。
function utf8_converter($array)
{
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
From: http://nazcalabs.com/blog/convert-php-array-to-utf8-recursively/
来自:http: //nazcalabs.com/blog/convert-php-array-to-utf8-recursively/
回答by Ethan Jinks O'Sullivan
If you are converting a dynamic CSV file, you can pass the URL through a parameter (url=http://example.com/some.csv
) and it will show you the most up-to-date version:
如果您要转换动态 CSV 文件,您可以通过参数 ( url=http://example.com/some.csv
)传递 URL ,它会显示最新版本:
<?php
// Lets the browser and tools such as Postman know it's JSON
header( "Content-Type: application/json" );
// Get CSV source through the 'url' parameter
if ( isset( $_GET['url'] ) ) {
$csv = explode( "\n", file_get_contents( $_GET['url'] ) );
$index = str_getcsv( array_shift( $csv ) );
$json = array_map(
function ( $e ) use ( $index ) {
return array_combine( $index, str_getcsv( $e ) );
}, $csv
);
}
else {
$json = "Please set the path to your CSV by using the '?url=' query string.";
}
// Output JSON
echo json_encode( $json );
回答by Ian D. Miller
Alternate solution that uses similar method as @Whirlwind's solution but returns a more standard JSON result (with named fields for each object/record):
替代解决方案使用与@Whirlwind 的解决方案类似的方法,但返回更标准的 JSON 结果(每个对象/记录都有命名字段):
// takes a string of CSV data and returns a JSON representing an array of objects (one object per row)
function convert_csv_to_json($csv_data){
$flat_array = array_map("str_getcsv", explode("\n", $csv_data));
// take the first array item to use for the final object's property labels
$columns = $flat_array[0];
for ($i=1; $i<count($flat_array)-1; $i++){
foreach ($columns as $column_index => $column){
$obj[$i]->$column = $flat_array[$i][$column_index];
}
}
$json = json_encode($obj);
return $json; // or just return $obj if that's a more useful return value
}
回答by Justin Parks
I liked @ian-d-miller's solution for converting the data into a key / value style format, but I kept running into issues with his code.
我喜欢@ian-d-miller 将数据转换为键/值样式格式的解决方案,但我一直遇到他的代码问题。
Here's what worked for me:
以下是对我有用的内容:
function convert_CSV_to_JSON($csv_data){
// convert csv data to an array
$data = array_map("str_getcsv", explode("\n", $csv_data));
// use the first row as column headers
$columns = $data[0];
// create array to hold our converted data
$json = [];
// iterate through each row in the data
foreach ($data as $row_index => $row_data) {
// skip the first row, since it's the headers
if($row_index === 0) continue;
// make sure we establish each new row as an array
$json[$row_index] = [];
// iterate through each column in the row
foreach ($row_data as $column_index => $column_value) {
// get the key for each entry
$label = $columns[$column_index];
// add this column's value to this row's index / column's key
$json[$row_index][$label] = $column_value;
}
}
// bam
return $json;
}
Usage:
用法:
// as is
$json = convert_CSV_to_JSON($csv);
// encoded
$json = json_encode($json);
回答by MoonCactus
The accepted answer uses file_get_contents()
to read the entire file as a string in memory, and then explode()
it to make it an array.
接受的答案用于file_get_contents()
将整个文件作为内存中的字符串读取,然后explode()
使其成为数组。
But it can be made faster, smaller in memory, and more useful:
但它可以做得更快、内存更小、更有用:
function ReadCsv($fn)
{
$lines= file($fn); // read file directly as an array of lines
array_pop($lines); // you can remove the last empty line (if required)
$json= json_encode(array_map("str_getcsv", $lines), JSON_NUMERIC_CHECK);
print_r($json);
}
Nb: I used JSON_NUMERIC_CHECK
here to avoid numbers being double quoted into strings. It also reduces the output size and it usually helps javascript on the other side (e.g. to compute or plot the data). Beware of phone numbers though!
注意:我JSON_NUMERIC_CHECK
在这里使用是为了避免将数字双引号括在字符串中。它还减少了输出大小,并且通常有助于另一侧的 javascript(例如计算或绘制数据)。不过要小心电话号码!
回答by SArnab
You can check to see if there was an error during JSON encoding using json_last_error(). Could you please try that first?
您可以使用json_last_error()检查在 JSON 编码期间是否存在错误。你能先试试吗?