Skip to content

Instantly share code, notes, and snippets.

@Vlasterx
Created August 13, 2016 12:11
Show Gist options
  • Save Vlasterx/17a7b0923b17326da6c6b69d3e25bbb3 to your computer and use it in GitHub Desktop.
Save Vlasterx/17a7b0923b17326da6c6b69d3e25bbb3 to your computer and use it in GitHub Desktop.
PHP: CSV to JSON
<?php
/*
You can rename this file to .JSON and add .htaccess with this content:
<Files *.json>
ForceType application/x-httpd-php
</Files>
*/
// CSV File
$filename = 'someExcel.csv';
// Function - CSV to JSON
function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 10240, ';', '"');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
// throw new Exception($file . ' doesn`t exist or is not readable.');
return array("error" => "Coordinates are not available");
}
return $rows;
}
$dataArray = csvToArray($filename);
// Send JSON headers
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json; charset=utf-8');
// Print out JSON
echo json_encode($dataArray, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment