Skip to content

Instantly share code, notes, and snippets.

@devfaysal
Last active February 6, 2023 10:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save devfaysal/9143ca22afcbf252d521f5bf2bdc6194 to your computer and use it in GitHub Desktop.
Save devfaysal/9143ca22afcbf252d521f5bf2bdc6194 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
@Sebascc
Copy link

Sebascc commented May 14, 2020

This script is genius. Thank you.

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