Export row from CSV file to JSON - php

I want to export a row in CSV file to JSON file with require : 1 line in CSV export 1 file JSON. I success to export file,but can't filter the row that i want to export. Can anyone help me?
<?php
header('Content-type: application/json');
$feed = 'jsondata_palpad.csv';
$keys = array();
$newArray = 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;
}
$data = csvToArray($feed, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
//Xuat file JSON
for ($i = 0; $i < 5; $i++) {
$json = json_encode($newArray[$i]);
echo $json . "<br />\n";
$filename = $data[$i][1] . ".json";
echo $filename . "<br />\n";
//echo "title[" . $data[$i][4] . "]";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
?>
If recommend = 2,it will export line whre id=2.
I want to export id,product_id,title,outline to JSON file.This is sample JSON file:
http://img839.imageshack.us/img839/5277/21527799.png
This is CSV file :
http://img690.imageshack.us/img690/1526/43004273.png

You are looping through all 6 lines of the csv file and saving them to the JSON file:
for ($i = 0; $i < 5; $i++) {
...
}
If you know what row number it is you want, don't loop through every row - just call the code inside the loop for that row. For example, if you wanted the 2nd row:
$row_we_want = 1;
$json = json_encode($newArray[$row_we_want]);
$filename = $data[$row_we_want][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
If you are unsure about which row it is and need to check each one, you could do so in the loop:
for ($i = 0; $i < 5; $i++) {
if (some_condition) {
$json = json_encode($newArray[$i]);
$filename = $i][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
}
Also it might be worth replacing 5 in your loop with the length of the array using the count function if it is not always a fixed length.

Related

Find a specific value in a CSV file using PHP

i have csv file available and i want to find value
Ex:
sku qty
11111 2 22222 4 333333 6
then i want to qty of 22222 sku
how can i will achieve it ?
my code is like below way ...
$handle = fopen("test.csv", "r");
//rewind($handle);
$count = 0;
while (($data = fgetcsv($handle, 0, ";")) !== false) {
$count++;
if ($count == 1) {
continue;
}
for ($i = 0, $j = count($data); $i < $j; $i++) {
$insert_csv = array();
$insert_csv['sku'] = $data[0];
$insert_csv['qty'] = !empty($data[1]) ? $data[1] : 0;
}
}
fclose($handle);
and my csv file output like this way ...
$file = file("test.csv");
for ($i = 2, $size = sizeof($file); $i < $size; $i++) {
$line = explode(';', $file[$i]);
if (trim($line[0]) === '22222') {
$answer = trim($line[1]);
continue;
}
}

Convert PHP script in Powershell script

I have to convert a PHP script in Powershell script.
I have current PHP script:
<?php
// read text file
$File = fopen("file.txt", "r") or die("Unable to open file!");
$typePers = array("Personale Viaggiante","Personale Interno");
$excludeFields = array("IT0006","IT0017","IT0077","Personale Viaggiante","Personale Interno","IT0105");
$emptyValue = "NaN";
$rowfinal = "";
// Output one line until end-of-file
while(!feof($File)) {
$row = explode(";",fgets($File));
$substring = "IT0006;IT0017;";
// left string
$lstr = "";
// right string
$rstr = "";
$type = array_intersect($row, $typePers);
$keys = array_keys($type);
if($keys == null) $type = $emptyValue;
else $type = $row[$keys[0]];
$j = 0;
for($i=0; $i<count($row); $i++){
if(in_array($row[$i],$excludeFields)){
unset($row[$i]);
$j++;
}
}
for($i=0; $i<22;$i++)$lstr .= $row[$i].";";
foreach($row as $k => $v)
if($k > 22)if(!empty($v))$rstr .= $v.";";
$rstr = substr($rstr,0,-1);
$substring .= $type;
$substring .= ";IT0077;NaN;IT0105;";
$rowfinal .= $lstr.$substring.$rstr;
}
$file = 'test.txt';
// Write the contents back to the file
file_put_contents($file, $rowfinal);
fclose($sapFile);
?>
I started writing this script in Powershell, but it is incomplete.
$File = Get-Content "file.txt"
$FilePath = "dump.txt"
$typePers = #("Personale Viaggiante","Personale Interno")
$excludeFields = #("IT0006","IT0017","IT0077","Personale Viaggiante","IT0105","Personale Interno")
$emptyValue = "NaN"
$rowfinal = ""
foreach($line in $File) {
[System.Collections.ArrayList]$row = $line -split ";"
$substring = "IT0006;IT0017;"
$lstr = ""
$rstr = ""
$ityp = -1;
for($i=0; $i -lt $row.Count; $i++){
if($typePers -contains $row[$i] ){
$ityp = $i
}
}
if($ityp -eq "-1"){
$type = "NaN"
}else{
$type = $row[$ityp]
}
$j = 0;
for($i=0; $i -lt $row.Count; $i++){
if($excludeFields -contains $row[$i]){
$row.RemoveAt($i)
$j++;
}
}
for($i=0; $i -lt 22;$i++) {
$lstr += $row[$i]+";"
}
$k = 0;
ForEach($v in $row) {
if($k -gt 22) {
if($v -ne ""){
$rstr += $v+";"
}
}
$k++
}
$rstr = $rstr.Substring(0,$rstr.Length-1)
$substring += $type
$substring += ";IT0077;NaN;IT0105;";
$rowfinal += $lstr+$substring+$rstr+"`r`n"
}
$rowfinal | Out-File -FilePath $FilePath
I have only problem with Remove method.
When I have IT0006 value in array, I have IT0105 duplicated...
To end, I have to add header columns for CSV file.
For example, I would to define an array with header:
$header = #('column1','column2',...,'column_n');
and add header at the file to export in CSV.

How to convert CSV to JSON with requires one line in CSV file will export one file JSON

I have a problem and need a help from you!
I want to convert CSV to JSON,and 1 line in CSV with export 1 file JSON (JSON's content is CSV line's content,and JSON's name is id of this line).
I try to do,but it's only display and download JSON.
Please give me a suggestion for this problem.
Thanks for your help!
<?php
header('Content-type: application/json');
$feed = 'jsondata_palpad.csv';
$keys = array();
$newArray = 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;
}
$data = csvToArray($feed, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
header("Content-type: application/json");
header("Content-Disposition: attachment; filename=test.json");
header("Expires: 0");
header("Pragma: no-cache");
echo json_encode($newArray);
?>
So you have a titled CSV file.
To read it, first convert the rows into an array:
$csv = array_map("str_getcsv", file($filename));
$head = array_shift($csv);
For conversion into an associative array:
$csv = array_map("array_combine", array_fill(0, count($csv), $head), $csv);
To generate the files:
foreach ($csv as $index => $row) {
file_put_contents("$index.json", json_encode($row));
}
Here the loop counter $index is used for generating the filenames.
See the manual for explanations on:
array_map
str_getcsv
file_put_contents
If you did want something else, write a more precise question next time.

Writing to multiple (splitting) CSV files with PHP

I'm using a simple function to write write arrays to a CSV-file, which look like this:
function writeToCSV($array) {
$fp = fopen('programmes.csv', 'a');
fputcsv($fp, $array);
fclose($fp);
}
Simple as a pie. However, is there anyway to know what line-number the pointer is at? Because I want to be able to after 1000 lines to begin writing to a new file. Why? Because I need to be able to import them to a database later with some memory constraints, and to parse a CSV-file with 15000 lines is a no-no.
function writeToCSV($array) {
$i = 1;
$j = 1;
$fp = fopen('programmes' . $j . '.csv', 'a');
foreach($array as $fields) {
if ($i % 1000 == 0) {
fclose($fp);
$fp = fopen('programmes' . $j . '.csv', 'a');
$j = $j + 1;
}
fputcsv($fp, $fields);
$i = $i + 1;
}
fclose($fp);
}
Try this:
count(file('programmes.csv'));
This will give you the number of lines in a file.
I haven't tried if this works, but i would do something like this:
<?php
function writeToCSV($array) {
// count lines in the current file
$linecount = 0;
$fh = fopen('programmes.csv','rb') or die("ERROR OPENING DATA");
while (fgets($fh) !== false) $linecount++;
fclose($fh);
$aSize = sizeof($array);
if (($linecount + $aSize) > 1000) {
// split array
$limit = 1000 - $linecount;
$a = array_slice($array, 0, $limit);
$b = array_slice($array, $limit);
// write into first file
$fp = fopen('programmes.csv', 'a');
foreach($a as $field) fputcsv($fp, $field);
fclose($fp);
// write into second file
$fp = fopen('programmes2.csv', 'a');
foreach($b as $field) fputcsv($fp, $field);
fclose($fp);
} else {
$fp = fopen('programmes.csv', 'a');
$idx = 0;
while ($linecount < 1000) {
// fill the file to the 1000 lines
fputcsv($fp, $array[$idx]);
++$linecount;
++$idx;
}
fclose($fp);
if ($idx != $aSize) {
// create new file
$fp = fopen('programmes.csv', 'a');
while ($idx< $aSize) {
// fill the file to the 1000 lines
fputcsv($fp, $array[$idx]);
++$idx;
}
fclose($fp);
}
}
}
?>

parsing a CSV as XML via PHP

I found this script which parses a CSV file to XML. Problem is it seems to only be getting the first line of data after the column headers.
function csv2xml($file, $container = 'data', $rows = 'row')
{
$r = "<{$container}>\n";
$row = 0;
$cols = 0;
$titles = array();
$handle = #fopen($file, 'r');
if (!$handle) return $handle;
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
if ($row > 0) $r .= "\t<{$rows}>\n";
if (!$cols) $cols = count($data);
for ($i = 0; $i < $cols; $i++)
{
if ($row == 0)
{
$titles[$i] = $data[$i];
continue;
}
$r .= "\t\t<{$titles[$i]}>";
$r .= $data[$i];
$r .= "</{$titles[$i]}>\n";
}
if ($row > 0) $r .= "\t</{$rows}>\n";
$row++;
}
fclose($handle);
$r .= "</{$container}>";
return $r;
}
Your CSV may be using Carriage Returns instead of Newlines, Try changing the "\n"s to "\r"s.

Categories