使用PHP将CSV转换为JSON

时间:2022-06-20 21:15:07

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($结果); //我看到所有数据

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 .... 

7 个解决方案

#1


53  

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);

#2


5  

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;

#3


3  

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/

#4


2  

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 );

#5


1  

data.csv

data.csv

Game,Skill
Treasure Hunter,pilipala
Rocket Launcher,bibobibo
Rocket Engine,hehehohoho

游戏,技能宝藏猎人,pilipala火箭发射器,bibobibo火箭发动机,hehehohoho

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"
    }
]

#6


1  

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
}

#7


-1  

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编码期间是否存在错误。你能先试试吗?

#1


53  

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);

#2


5  

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;

#3


3  

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/

#4


2  

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 );

#5


1  

data.csv

data.csv

Game,Skill
Treasure Hunter,pilipala
Rocket Launcher,bibobibo
Rocket Engine,hehehohoho

游戏,技能宝藏猎人,pilipala火箭发射器,bibobibo火箭发动机,hehehohoho

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"
    }
]

#6


1  

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
}

#7


-1  

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编码期间是否存在错误。你能先试试吗?