在 PHP 中从远程 CSV 中获取 JSON 数组


get json array from remote csv in php

对于我的一个 php 代码,我希望 json 数组如下来自 php 中的远程 csv 文件。

远程 csv 文件:www.xyz.com/dir/records.csv

NAME    Age ID
Jhon    45  101
Bhil    42  102
Tone    41  103

我想要一个将此 CSV 文件转换为 JSON 数组的函数

像这样:

$json = '{"records": 
       [
         {"Name":"Jhon", "Age":"45", "id":"101"},
         {"Name":"Bhil", "Age":"42", "id":"102"},
         {"Name":"Tone", "Age":"41", "id":"103"},
       ]
    }';

请指导我,如何对上面的csv文件进行编码,以获取以下php代码的上述json数组。

$myjson = json_decode($json, true);  
  foreach ( $myjson['records'] as $row ) {  
                        if ($row['id'] =='101') { 
                          foreach ( $row as $field => $value ) {  
                               // do the work here
                             }
                   }
         }

这是解决方案,您可以在csvToJson()函数中相应地修改输出数组格式

<?php
     function csvToJson($filename) {
            $handle = fopen($filename,"r");
            $i=0;
            if($handle) {
                while(($line = fgetcsv($handle,1000,",","'")) !== FALSE)
                {
                    if($i == 0) {
                        $c = 0;
                        foreach($line as $col) {
                            $cols[$c] = $col;
                            $c++;
                        }
                    } else if($i > 0) {
                        $c = 0;
                        foreach($line as $col) {
                            $data[$i][$cols[$c]] = $col;
                            $c++;
                        }
                    }
                    $i++;
                }
            }
            $data2['records'] = array($data);       
            fclose($handle);
            // return json_encode($data2);  /*you don't have to convert it into json if you want to use it in your php foreach loop you can directly return this*/ 
            return json_encode($data2);
        }
        $json = csvToJson('records.csv');
        echo "<pre>";
        print_r($json);
    ?>

如果您将 csv 存储在本地或 fopen 支持主机上的远程地址,则可以编写与此类似的函数:

<?php
//pass the filename and optional the separator used in your csv to this function
function csvToJson($filename, $separator = ";")
{
    //create the resulting array
    $result = array("records" => array());
    //check if the file handle is valid
    if (($handle = fopen($filename, "r")) !== false)
    {
        //check if the provided file has the right format
        if(($data = fgetcsv($handle, 4096, $separator)) == false || ($data[0] != "NAME" || $data[1] != "Age" || $data[2] != "ID"))
        {
            throw new InvalidImportFileFormatException(sprintf('The provided file (%s) has the wrong format!', $filename));
        }
        //loop through your data
        while (($data = fgetcsv($handle, 4096, $separator)) !== false)
        {
            //store each line in the resulting array
            $result['records'][] = array("Age" => $data[0], "Name" => $data[1], "Id" => $data[2]);
        }
        //close the filehandle
        fclose($handle);
    }
    //return the json encoded result
    return json_encode($result);
}

如果您必须首先从远程地址获取 csv,请使用 curl 将其临时保存。

如果您必须从远程服务器访问 csv 文件,您可以使用它,您也可以使用 cURL 将文件保存在您的服务器上,然后使用 csvToJson() 函数(如果您在服务器上使用 curl 下载文件,请注释函数的前四行)。

    function csvToJson($filename) {
                $content = file_get_contents('www.xyz.com/dir/records.csv');
// $content = file_get_contents('https://docs.shopify.com/manual/your-store/products/product_template.csv');  /* demo URL *-/
                $handle = fopen($filename,"w");
                fwrite($handle, $content);
                fclose($handle);
                $handle = fopen($filename,"r");
                $i=0;
                if($handle) {
                    while(($line = fgetcsv($handle,1000,",","'")) !== FALSE)
                    {
                        if($i == 0) {
                            $c = 0;
                            foreach($line as $col) {
                                $cols[$c] = $col;
                                $c++;
                            }
                        } else if($i > 0) {
                            $c = 0;
                            foreach($line as $col) {
                                if($col != ''){
                                    $data[$i][$cols[$c]] = $col;
                                }
                                $c++;
                            }
                        }
                        $i++;
                    }
                }
                $data2['records'] = array($data);       
                fclose($handle);
                return json_encode($data2);
            }
            $json = csvToJson('records.csv');
            echo "<pre>";
            print_r($json);