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.
Related
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;
}
}
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.
I would like to split a very large CSV file (20 000 lines) to be able to put everything in my MySQL database (after I use cronjob for load the php file every hours).
So I have found code to split my file :
$inputFile = 'Shipping.csv';
$outputFile = 'output';
$splitSize = 1000;
$in = fopen($inputFile, 'r');
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
}
$data = fgetcsv($in);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
I have tried to do this but they don't work :
require_once dirname(__DIR__).'/pdo.php';
$inputFile = 'Shipping.csv';
$outputFile = 'output';
$splitSize = 1000;
//open uploaded csv file with read only mode
$in = fopen($inputFile, 'r');
//skip first line
fgetcsv($in);
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
}
$data = fgetcsv($in);
if ($data){
fputcsv($out, $data);
}
while(($line = fgetcsv($out)) !== FALSE){
//check whether member already exists in database with same email
$prevQuery = "SELECT id FROM shipbp WHERE license = '".$line[1]."'";
$prevResult = $bdd->query($prevQuery);
if($prevResult->rowCount() > 0)
{
$bdd->query("UPDATE shipbp SET license = '".$line[0]."'");
}
else{
$bdd->query("INSERT INTO shipbp (license) VALUES ('".$line[0]."')");
}
}
$rowCount++;
}
fclose($out);
CSV file look like :
P135460,002,00003,250,AS44563,0.35,,Blabla,17/3/2017 00:00:00,SB,Blabla
How I can do ?
Thank you for your help
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.
I need to upload a file (in this case a csv file) and load the contents of it into the following function:
function csv2xml($file, $container = 'data', $rows = 'row')
{
$r = "<{$container}>\n";
$row = 0;
$cols = 0;
$titles = array();
while (($data = fgetcsv($file, 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++;
}
$r .= "</{$container}>";
return $r;
}
This is how im calling the function
csv2xml($_POST['file'], $container = 'wholething', $rows = 'item');
In the form the input box's name is file
I get the following Warning:
fgetcsv() expects parameter 1 to be resource, null given
You need to open the file first, eg:
$filePointer = fopen($file, "r"); // read-only
Then use:
while (($data = fgetcsv($filePointer, 1000, ',')) !== FALSE)
to retrieve your data.
Note that you'll probably want to check out PHP's file upload information to make sure you're using the $_FILES array to get your uploaded file. and not just $_POST.
#richsage already answered the question. If you still have problems, visit the documentation for a working example. I just wanted to point out your function call:
csv2xml($_POST['file'], $container = 'wholething', $rows = 'item');
Although it works, this is not how you call functions.
csv2xml($_POST['file'], 'wholething', 'item');
Is what you mean to do.