PHP remove all newlines and spaces from a csv - php

I am trying to convert a CSV to JSON using this awesome Jist: https://gist.github.com/robflaherty/1185299
I have been given a very CSV from a very antiquated procedural programming language. The CSV can ONLY be produced as follows.
I need to strip out the second line which is a blank newline and ideally, I'd like to strip out all the extra spaces for each line:
Series, SKU, Stock
01000 , 01000-1116 , 98
01000 , 01000-1132 , 0
01000 , 01000-116 , 1000
01000 , 01000-1164 , 3880
01000 , 01000-12 , 2040
01000 , 01000-132 , 2240
01000 , 01000-1332 , 545
01000 , 01000-1364 , 50
I've tried every combination in my small arsenal to get this to work. preg_replace, trim etc.
Has anyone got any advice? Here is the section of the Jist that is handling the rows:
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;
}
I hope someone can help! Thanks in advance for taking a look.

You need to check $lineArray and use trim() function as in the following code:
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
if (count($lineArray) == 1 && is_null($lineArray[0])) {
continue;
}
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = trim($lineArray[$j]);
}
$i++;
}
fclose($handle);
}
return $arr;
}

Try this. It skips empty lines and trims values.
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
if(count($lineArray)==1) continue; //skip empty line (will fail if file will have only one column)
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = trim($lineArray[$j]); //trim value
}
$i++;
}
fclose($handle);
}
return $arr;
}

Try this code:
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++) {
if ($lineArray[$j] !== '') {
$arr[$i][$j] = $lineArray[$j];
}
}
$i++;
}
fclose($handle);
}
return $arr;
}

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;
}
}

Getting a CSV cell full value in PHP

Am reading a CSV file using PHP, i get all the values for each row but some columns having long data displays something like this 9.21008E+15
I don't know how to get the complete value which is suppose to be this 9210080000000000
if (($handle = fopen("Test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$num = count($data);
$tb_row = "";
for ($c=0; $c < $num; $c++) {
$tb_row .= $data[$c].",";
}
$new_row = substr($tb_row, 0, -1);//removing the comma at the end of line...
//explode and assign values then insert
$each_col = explode(',', $new_row);
$Device_state = $each_col[0];
$udid = $each_col[8];
$imsi = $each_col[9];
$imei = $each_col[10];
echo "$imsi || $imei"."<br />";
}
}
Adding a prefix to the cells having this issue solved the issue (')
You need just convert it back into integer value
if (($handle = fopen("Test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$num = count($data);
$tb_row = "";
for ($c=0; $c < $num; $c++) {
if (strpos($data[$c], 'E+'))
$data[$c] = intval((float)$data[$c]);
$tb_row .= $data[$c].",";
}
$new_row = substr($tb_row, 0, -1);//removing the comma at the end of line...
//explode and assign values then insert
$each_col = explode(',', $new_row);
$Device_state = $each_col[0];
$udid = $each_col[8];
$imsi = $each_col[9];
$imei = $each_col[10];
echo "$imsi || $imei"."<br />";
}
}

PHP beginner - issues with associative arrays

I'm trying to take a file of id numbers and find the names associated with those numbers from a different file and print a csv in the form id,name.
The Def.csv file is in the form
1;128;34;64;Uppland,
2;0;36;128;Östergötland,
3;128;38;192;Småland,
WIth the first number being the ID and the last field the name.
The IDs.csv is just IDs in no specific order with a comma and new line. ie.
12, \n
Here's the (updated, bad) script:
<?php
$ID;
$names;
$both = array();
$row = 0;
echo ("1\n");
if (($handle = fopen("IDs.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$ID[$row] = $data[0];
$row++;
//print_r($ID);
}
}
print_r($ID);
fclose($handle);
if (($handle = fopen("Defs.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$Names = $data[4];
// DEBUG, works// echo "$Names";
}
}
fclose($handle);
for ($c = 0; $c < $row; $c++)
{
$Both[$ID[$c]] = $Names[$ID[$c]];
}
foreach ($Both as $key => $value)
{
echo "$key,$value\n";
}
?>
This is my current output
Array
(
[0] => 2
[1] => 3
[2] => 1
)
2,t
3,l
1,u
for the small test case here it should be 2,Östergötland 3,Småland and 1,Uppland

PHP Read from a CSV-file

I have a simple CSV-file which looks like this:
Value:
AAA
Value:
BBB
Value:
AAA
I want to count the number of times a certain value shows up (e.g. AAA).
To start, I want to get the lines which read "Value:" and just echo the following line "line[$i+1] which would be the corresponding value.
Here's the code:
<?php
$file_handle = fopen("rowa.csv", "r");
$i = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$line[$i] = $line_of_text[0];
if($line[$i] == "Value:"){
echo $line[$i+1]."<br />";
}
$i++;
}
fclose($file_handle);
?>
The outcome should look like this:
AAA
BBB
AAA
Unfortunately, this doesn't work..It just gives me "<*br /">s
If you are printing on command line or a file, you need to use \n instead of <br/>. That only works if your output is HTML. Also every time you want to move two lines. the logic should look like this:
if($line[$i] == "Value:"){
echo $line[$i+1]."\n"; // add a new line
}
$i+=2; // you want to move two lines
This doesn't look like a normal everyday CSV file, but here's an example that should work.
$fh = fopen('rowa.csv', 'r');
$OUT = array();
$C = 0;
while( ! feof($fh) ) {
// read 1 line, trim new line characters.
$line = trim(fgets($fh, 1024));
// skip empty lines
if ( empty($line) ) continue;
// if it's a value line we increase the counter & skip to next line
if( $line === 'Value:' ) {
$C++;
continue;
}
// append contents to array using the counter as an index
$OUT[$C] = $line;
}
fclose($fh);
var_dump($OUT);
This is not a CSV file. The file() command will load the lines of a file into an array. The for loop prints every second line.
$lines = file("thefile.txt");
for ($i = 1; $i < count($lines); $i = $i + 2) {
echo $lines[$i] . "<br/>" . PHP_EOL;
}
As PHP.net example provides, you can use this modified code:
<?php
$count = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (!strcmp($data[$c], 'Value:')) continue;
if (!strcmp($data[$c], 'AAA')) $count++;
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
UPDATE
Try this new code, we use the value as array key and increment the count for that "key".
<?php
$counts = array();
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (strcmp($data[$c], 'Value:'))
{
if (!isset($counts[$data[$c]]))
{
$counts[$data[$c]] = 0;
}
$counts[$data[$c]]++;
}
else
{
// Do something
}
}
}
fclose($handle);
}
var_dump($counts);
?>
You can print the array like this:
foreach ($counts as $key => $count)
{
printf('%s: %d<br/>' . "\n", $key, $count);
}

reading first 5 fields of csv file in php

I am confused on how to read a csv file in php ( only the first 4 fields) and exclude the remaining fileds.
Sno,Name,Ph,Add,PO
1,Bob,0102,Suit22,89
2,Pop,2343,Room2,78
I just want to read first 3 fileds and jump to next data. cannot figure out how to do through fgetcsv
any help?
Thanks,
I added a comment to the sample fgetcsv code for you:
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
// iterate over each column here
for ($c=0; $c < $num; $c++) {
// handle column data here
echo $data[$c] . "<br />\n";
// exit the loop after 3rd column parsed
if ($c == 2) break;
}
++$row;
}
fclose($handle);
}
Here's a way to do it without the fgetcsv function:
$lines = file('data.csv');
$linecount = count($lines);
for ($i = 1; $i < $linecount; $i++){
$fields = explode(',', $lines[$i]);
$sno = $fields[0];
$name = $fields[1];
$ph = $fields[2];
$add = $fields[3];
}

Categories