Convert CSV to JSON using PHP

Конвертация CSV в JSON на PHP

Учусь конвертировать csv файлы в формат json на php(который тоже знаю не очень), большая просьба помочь с алгоритмом. есть следующий csv фрагмент который упакован в файл data.csv :

Name;Art;Price Товар 1;1001;10639 Товар 2;1002;23387 Товар 3;1003;20129 Товар 4;1004;14005 Товар 5;1005;49594 Товар 6;1006;20181 Товар 7;1007;37999 Товар 8;1008;29357 Товар 9;1009;49505 Товар 10;1011;11047 Товар 11;1012;18564 
$csv = array_map('str_getcsv', file('data.csv')); 
array(12) < [0]=>array(1) < [0]=>string(14) "Name;Art;Price" > [1]=> array(1) < [0]=>string(23) "Товар 1;1001;10639" > [2]=> array(1) < [0]=>string(23) "Товар 2;1002;23387" > [3]=> array(1) < [0]=>string(23) "Товар 3;1003;20129" > [4]=> array(1) < [0]=>string(23) "Товар 4;1004;14005" > [5]=> array(1) < [0]=>string(23) "Товар 5;1005;49594" > [6]=> array(1) < [0]=>string(23) "Товар 6;1006;20181" > [7]=> array(1) < [0]=>string(23) "Товар 7;1007;37999" > [8]=> array(1) < [0]=>string(23) "Товар 8;1008;29357" > [9]=> array(1) < [0]=>string(23) "Товар 9;1009;49505" > [10]=> array(1) < [0]=>string(24) "Товар 10;1011;11047" > [11]=> array(1) < [0]=>string(24) "Товар 11;1012;18564" > > 

Понимаю что следующей итерацией мне необходимо данный массив перебрать и привести к образцу, но не понимаю как это сделать. Собственно просьба о помощи в подсказке правильного цикла для данного действия. А может быть я что то делаю не так, Спасибо

Источник

Convert CSV To JSON Using PHP (With Header Row As Keys)

Hi! Here is the php script to convert csv to json with header row as keys. Both csv and json are used to store data but json is little more verbose and human readable and has become popular data exchange format among modern web services. Converting csv data into json format is little tricky especially if you want your json to be properly formatted as key:value pairs. The csv header row should be used as keys and the subsequent rows as values to form json string.

Читайте также:  Шрифт

Unfortunately there is no direct way to do this but likely there is a workaround to bring out the desired result. The method used here is by far the most effective solution to convert csv to json with header row as keys.

convert-csv-to-json-php

Converting CSV to JSON using PHP

Let’s take a sample csv file with header and some rows and convert it to json using php script.

Data.csv

Id,Name,Position,Salary 1,Suki Burks,Developer,$114500 2,Fred Zupers,Technical Author,$145000 3,Gavin Cortez,Team Leader,$235500

PHP Function to Convert CSV to JSON

This is the php function to convert csv to json representation. The function takes up a csv file as parameter, stores the headers as a separate key array and read the subsequent rows one by one into an array and finally combine both key and data array to form a proper key-value pair representation.

 //read csv headers $key = fgetcsv($fp,"1024",","); // parse csv rows into array $json = array(); while ($row = fgetcsv($fp,"1024",",")) < $json[] = array_combine($key, $row); >// release file handle fclose($fp); // encode array to json return json_encode($json); > ?>
  • The function fgetcsv($fp,»1024″,»,») reads a row from the csv file into an array. The second parameter «1024» is the maximum character length of the csv row and the third parameter «,» represents the column delimiter.
  • The function json_encode() encodes the php array into json string.

Function Usage

Call the above php function like this to convert csv to json.

If you want json to be stored in a separate file, then open a file and write to it. Check this tutorial to know how to write to a json file.

Thus with this small php utility function you can very easily convert csv to json string.

Источник

Webslesson

PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter, Laravel Tutorial

Friday, 16 October 2020

How to Convert CSV to JSON in PHP

This is simple and short tutorial on How do we convert CSV file data into JSON format in PHP. In this world of web programming, sometimes we have to make feature like fetch data from CSV file and insert that CSV file data into Mysql database then at that time we have need to convert CSV to JSON. The main purpose of this tutorial is to learn how can we easy way to convert CSV data or file to JSON object using PHP script.

Advantages of CSV

  1. CSV files can be opened or edited by text editors like notepad.
  2. In data-warehouse, CSV follows a reasonably flat, simple schema.
  3. Any programing language to parse CSV data is trivial, generating it’s extremely easy.
  4. CSV is safe and may clearly differentiate between the numeric values and text. CSV doesn’t manipulate data and stores it as-is.
  5. In CSV, you write column headers just one occasion where as in Excel, you’ve got to possess a start tag and end tag for every column in each row.
  6. Importing CSV files are often much faster, and it also consumes less memory.
  7. It’s easy to programmatically manipulate CSV since, after all, they’re simple text files.
  8. CSV are often opened with any text editor in Windows like notepad, MS Excel, Microsoft Works 9, etc.

Advantages of JSON

  1. JSON is a portable that means it can be parse and write are available in many programming languages like JavaScript.
  2. By using JSON we can online transfer large data from source to destination in the form of array or objects.
  3. IN JSON we can transfer data in plain text or unformatted data like comma speratted or delimited data.
  4. JSON is better that XML, this is because it has more sufficient space than XML data structure.
  5. JSON has no tag name and it has structure which is nested braces instead of verbose tags.
  6. In exchange of data JSON is faster than XML.

So here we have seen benefits of CSV and JSON data and both are mainly used for data exchange. But if you have work on any web services than JSON data is mostly used for transmit or exchange of data on the web. So if you have data in CSV file and you have to exchange that data then you must convert that data into JSON format and you can easily exchange data online.

In PHP language there many functions are available for parse or read data from CSV file and then convert that data into PHP array and lastly for convert data into JSON then we can use json_encode() function.

Sample Input CSV Data

 Company Name,Address,City,State,ZIP/PIN CODE,Country,Website,Industry,First Name,Last Name,Phone Number,Designation,Email Cougar Investment,3570 Thunder Road,Mountain View,CA,94041,USA,dealtechs.com,Animal care and service worker,Devin,Taylor,650-564-1816,Animal care and service worker,DevinRTaylor@armyspy.com Robert Hall,1729 Lyndon Street,Slatington,PA,18080,USA,toksalgida.com,Media,Ruby,Gibson,610-767-5251,News anchor,RubyBGibson@armyspy.com 

index.php

  $count = count($data_array) - 1; for($j = 0; $j < $count; $j++) < $data = array_combine($column_name, $data_array[$j]); $final_data[$j] = $data; >header('Content-disposition: attachment; filename='.$file_name.'.json'); header('Content-type: application/json'); echo json_encode($final_data); exit; > else < $error = 'Only .csv file allowed'; > > else < $error = 'Please Select CSV File'; >> ?>       


Convert CSV to JSON using PHP


Select CSV File

'.$error.'
'; > ?>
Select File



Источник

How To Convert CSV To JSON Using PHP?

In this tutorial, we learn how to convert CSV to JSON format in PHP. This tutorial is very easy to explain PHP convert CSV to JSON. we will learn how to convert CSV data or file into a JSON object in PHP. This tutorial has a purpose to shows you an easy way to convert CSV data or file to JSON object in PHP. This is a simple and short tutorial on How to CSV to JSON in PHP. we have to make features like fetch data from CSV file and insert that CSV file data into the Mysql database. we have to need to convert how to convert CSV to JSON. The main purpose of this tutorial is to learn how to convert CSV to JSON.

How To Convert CSV To JSON Using PHP? -Step By Step

       


Select File



 $count = count($data_array) - 1; for($j = 0; $j < $count; $j++) < $data = array_combine($column_name, $data_array[$j]); $final_data[$j] = $data; >header('Content-disposition: attachment; filename='.$file_name.'.json'); header('Content-type: application/json'); echo json_encode($final_data); exit; > else < $error = 'Only .csv file allowed'; > > else < $error = 'Please Select CSV File'; >> ?>

How To Convert CSV To JSON Using PHP? -Step By Step

Like the CSV file that you have selected, it will be converted as an example in JSON. We learn to convert CSV to JSON, see example in JSON below.

[ < "Name": "Ajay kumar", "email": "[email protected]", "City": "New delhi", "State": "delhi", "ZIP/PIN CODE": "110001", "Country": "INDIA", "Website": "phpcodingstuff.com" >, < "Name": "Abhaykumar", "email": "[email protected]", "City": "New delhi", "State": "delhi", "ZIP/PIN CODE": "110001", "Country": "INDIA", "Website": "phpcodingstuff.com" > ]

Источник

Оцените статью