For one of my php code, i want the json array as following from remote csv file in php.
The remote csv file: www.xyz.com/dir/records.csv
NAME Age ID
Jhon 45 101
Bhil 42 102
Tone 41 103
I want a function which converts this CSV file to a JSON array
Something Like this:
$json = '{"records":
[
{"Name":"Jhon", "Age":"45", "id":"101"},
{"Name":"Bhil", "Age":"42", "id":"102"},
{"Name":"Tone", "Age":"41", "id":"103"},
]
}';
Kindly guide me, how to incopporate the above csv file to get the above json array for the follwoing php code.
$myjson = json_decode($json, true);
foreach ( $myjson['records'] as $row ) {
if ($row['id'] =='101') {
foreach ( $row as $field => $value ) {
// do the work here
}
}
}
Here is the solution, You can modify your output array format accordingly inside csvToJson() function
<?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);
?>
You can write a function similiar to this one if you have the csv stored somewhere local or fopen supports remote addresses on your host:
<?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);
}
If you have to fetch your csv first from a remote address, use curl to save it temporary.
You can use this if you have to access csv file from remote server either you can also user cURL to save file on your server and then use the csvToJson() function(comment first four lines of the function if you download file using curl on your server).
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);