Skip to content

Instantly share code, notes, and snippets.

@rduarte
Forked from devfaysal/csv-to-json.php
Created January 18, 2020 15:37
Show Gist options
  • Save rduarte/001e0b301d7eff57f97413d92b7d5205 to your computer and use it in GitHub Desktop.
Save rduarte/001e0b301d7eff57f97413d92b7d5205 to your computer and use it in GitHub Desktop.
CSV to JSON
<?php
/*
* Converts CSV to JSON
* Example uses the csv file of this gist
*/
$feed="https://gist.githubusercontent.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194/raw/ec46f6c2017325345e7df2483d8829231049bce8/data.csv";
//Read the csv and return as array
$data = array_map('str_getcsv', file($feed));
//Get the first raw as the key
$keys = array_shift($data);
//Add label to each value
$newArray = array_map(function($values) use ($keys){
return array_combine($keys, $values);
}, $data);
// Print it out as JSON
header('Content-Type: application/json');
echo json_encode($newArray);
SKU Name Stock Regular price
20106 UGREEN Micro HDMI male to HDMI female Adapter 38
20107 UGREEN HDMI female to female adapter 1 200
20144 UGREEN Micro HDMI+Mini HDMI male to HDMI female adapter 48 250
20215 UGREEN USB 2.0 to SATA Hard Driver converter cable with 12V 2A power adapter 50CM 5 1430
20231 UGREEN USB 3.0 to SATA Converter cable with 12V 2A power adapter 50CM 2 1700
20324 UGREEN Digital device organizer travel storage bag-M Size 0 1200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment