使用文件处理的json编码与php

I was just trying to encode the csv's file data into json with php. Following was the question:-

function signature:
function parseCSV($path_to_file=null,$keys = array()){...}
Input parameters:
$path_to_file : a system dependent file system path.
$keys : an array of strings
The function must:
•Determine whether the file is ASCII or UTF-8 encoded text.
•Validate that the file generally conforms to RFC 4180.
•Search for the existence of a "Header Row" containing arbitrary column titles by searching each column for the existence of one key from the array of keys passed to the function.
•When the header row is identified, the it will be processed to create and return the JSON encoded object described below.
$structure = array('signature' => $signature,
'header_row' => $header_row,
'headers' => array(
array('column' => $column,
'header' => $header),
...
array('column' => $column,
'header' => $header)
)
Fields in Structure:
$signature :the MD5 hex encoded value of the concatenation of all of the columns in the header row, using no "glue".
$header_row: the zero based row number of the identified header,.
$headers: an array of column definition arrays.
$column: the zero based column number for the column header.
$header: the text value of the column header
Example:
Input CSV ("foo.csv"):
Provided by ZIP Code Solutions
"Address","City", "State","Zip Code"
"100 Main St.","Anywhere", "WA","98033"
...
"200 Second Ave..","Nowhere", "WA","98011"
$json = parseCSV("foo.csv", array('City','foo','bar'));
returns:
{
"signature": "bb0672c104e87c8852917cb220f15e7a",
"header_row": 1,
"headers": [
{
"column": 0,
"header": "\"Address\""
},
{
"column": 1,
"header": "\"City\""
},
{
"column": 2,
"header": "\"State\""
},
{
"column": 3,
"header": "\"Zip Code\""
}
]
}

Here is what I did:

  //function for checking the format of file whether it is in ascii or UTF-8
    function isAscii($file)
    {
        return (mb_detect_encoding($file) == "ASCII"|| mb_check_encoding($file,"UTF-8")) ? true: false;
    }
    //function for parsing the CSV file based on the keys that we pass
    function parseCSV($path_to_file=NULL,$keys=array())
    {
    //    @var for storing MD5 hash of columns
        $signature;
    //    @var for storing the wholw structure of array
        $structure=array();
    //    @var for row numbers
        $row_number =1;
    //    @var for column number
        $col_number =0;
        if(!file_exists($path_to_file))
        {
            echo "File does not exists";
            return false;
        }
        if(isAscii($path_to_file))
        {
            $file = fopen($path_to_file , "r") or die("Could not open file");
            while(!feof($file))
            {
                $row = fgetcsv($file);
    //            @var for holding matched headers
                $headers=array();
    //               @var for holding the matched headers of current row in loop temporarily
                $dumy=array();
    //            @var for holding the matched column names
                $str="";
                if(is_array($row) || is_object($row)){
                    foreach($row as $value)
                    {
                        if(in_array($value,$keys))
                        {
                            $str.=$value.",";
                            $dumy =array("column"=>$col_number,
                                          "header"=>$value);
                            array_push($headers,$dumy);
                        }
                        $col_number++;
                    }
                    if(!empty($str)) {
                        $signature = md5($str,false);
                        $dumy_structure=array("signature"=>$signature,
                                              "header_row"=>$row_number,
                                              "headers"=>$headers);
                        array_push($structure,$dumy_structure);
                     }
                }
                $col_number=0;
                $row_number++;
            }
            fclose($file);
            return json_encode($structure);
        }
    }


    //dumy keys for testing
    $keys = array("Address","City","State","Zip Code");

    echo $json = parseCSV('test.csv',$keys);

I just want to know is there any other best way to solve the same problem or if anyone can help me out to find out what are the draw backs of my code

To concert CSV to JSON in PHP is actually quite simple:

$file="mysqlTable.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("
", $csv));
print json_encode($array);

The first two lines are simple, and do not need any explaining.

Convert CSV into an array

The third line, converts the csv file into a multidimensional array

$array = array_map("str_getcsv", explode("
", $csv));

Explode the csv string on line ends into an array of lines, and convert the lines themselves with the safe native function str_getcsv to an array. Although it is tempting to parse a line of csv with

explode(",", $line);

always use the native functions for csv like, str_getcsv.

Convert an array into JSON

Once you have the $array, simply convert it to JSON:

print json_encode($array,JSON_PRETTY_PRINT);

JSON_PRETTY_PRINT is optional and will print the JSON with whitespace.