从php远程csv获取json数组

时间:2015-03-12 06:25:31

标签: php arrays json csv

对于我的一个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文件来获取上面的json数组以供下面的php代码使用。

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

3 个答案:

答案 0 :(得分:1)

这是解决方案,您可以在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);

    ?>

答案 1 :(得分:0)

如果您将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将其临时保存。

答案 2 :(得分:-1)

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

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