Skip to content

Instantly share code, notes, and snippets.

@robflaherty
Created September 1, 2011 02:26
Show Gist options
  • Save robflaherty/1185299 to your computer and use it in GitHub Desktop.
Save robflaherty/1185299 to your computer and use it in GitHub Desktop.
Convert CSV to JSON
<?php
/*
* Converts CSV to JSON
* Example uses Google Spreadsheet CSV feed
* csvToArray function I think I found on php.net
*/
header('Content-type: application/json');
// Set your CSV feed
$feed = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0Akse3y5kCOR8dEh6cWRYWDVlWmN0TEdfRkZ3dkkzdGc&single=true&gid=0&output=csv';
// Arrays we'll use later
$keys = array();
$newArray = array();
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
// Do it
$data = csvToArray($feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
// Add Ids, just in case we want them later
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
// Print it out as JSON
echo json_encode($newArray);
?>
@gruckion
Copy link

Licensing? am I free to use this or are there any restrictions?

@francolaiuppa
Copy link

We executed this for CSV dataset that we got and the results were incredible. Thank you!!!!!!

@ram-you
Copy link

ram-you commented Jun 13, 2014

Thank you. Saved me.

@dev-ext
Copy link

dev-ext commented Aug 10, 2014

Thank you. I make my portfolio based on your script.

@joshuaiz
Copy link

This is exactly what I needed.
It may be obvious but for anyone who needs to access the PHP created json via javascript, just use this:

<?php $json = json_encode($newArray); ?>
<script>
var $json = <?php echo $json; ?>;
// do your magic here
</script>

@albert-massey
Copy link

Thanks a million Rob! :)

@afenix
Copy link

afenix commented Jun 19, 2015

So awesome. Thanks much for the share! I was going to have to refactor a bunch of code, and this worked like a charm. I hope I can repay the favor one day.

@UTCWebDev
Copy link

I have a nested/setted JSON format I need to produce... Can anyone suggest how to format a spreadsheet to produce this: http://mapplic.com/plugin/mall.json

Or would that require a set of spreadsheets/CSVs?

@ur92
Copy link

ur92 commented Feb 25, 2016

Great Gist!

I forked it and shortened the csvToArray function to this:
$data = array_map('str_getcsv', file($feed));
as this is more compact and performance should be better.

Tested => works!

@hotgrandma69
Copy link

This is exactly what I was looking for! Thanks a million!!!!

@g4spow
Copy link

g4spow commented Jun 9, 2016

My file path for my images is folder/imagename.jpg.

When I run this great script, this is the only thing throwing an error. The path come out as folder/imagename.jpg

Here is the screenshot of the issue:
http://i.imgur.com/t0GQAEv.jpg

Also, can the output be saved to a .json file rather than within the PHP?

@JohanDuran
Copy link

Really useful. Thanks.

@imsabin
Copy link

imsabin commented Jul 2, 2017

hi, my server has disabled fopen. so is there any alternative like using curl to get the same result??

@aarondunphy
Copy link

Thanks for this.

Tried using it in Laravel for my seeders with a csv file and ended up needing to move the csvToArray function outside and call it via $this->csvToArray() due to a redeclare issue.

@devfaysal
Copy link

Great gist. I took inspiration from this and made a simplified version.
https://gist.github.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194

@chanakaDe
Copy link

Can anyone tell me why I'm getting "/ufeff" in my JOSN array ?

@bhavin-rb
Copy link

Hi, Can anyone please help me with this problem of:
Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'interest-cohort'.

API:
https://bhavin-rb.github.io/math_quiz_1/algebra1_api.json

App:
https://bhavin-rb.github.io/algebra1_quiz/

The quiz app works fine from local host and when I published on Github it gave the above error. I made a json file as API and fetching the API that contains the questions and answer options from Github pages. As I said, locally everything is working fine.
Kindly, assist to resolve this problem. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment