CSV league not skipping empty records - php

I am using PHPleague to parse csv and insert it to the database. https://csv.thephpleague.com/
And I have code as follows:
$csv = Reader::createFromPath($path, 'r');
$csv->skipEmptyRecords();
$csv->setHeaderOffset(0);
$csv_header = $csv->getHeader();
$stmt = (new Statement())
->offset('0')
->limit('20')
;
$records = $stmt->process($csv);
foreach($records as $record){
print_r($record); // this show that it has processed empty records as well
}
exit();
I could trim the empty records myself as well as by calling following function as $records = $this->trimArray($records);
public function trimArray($arr)
{
$final = array();
foreach($arr as $k => $v)
{
if(array_filter($v)) {
$final[] = $v;
}
}
return $final;
}
However, I want it to be trimmed before than that. Instead of adding my own layer to filter it is there anyway on csvleague to skipemptyrecords. I have tried with $csv->skipEmptyRecords(); but it is not skipping empty records. Am I doing anything wrong?
My file looks like:
I want to skip all those empty records.

I had a simple experience with League\CSV and tried to catch the data from a csv file. The package codes depend strongly on the version that you have installed. So at first step check the version of League. I think you should read the League documentation page about stream filters.
https://csv.thephpleague.com/9.0/connections/filters/

Related

loop csv column values and concatenate values to new column in php

I am new to PHP and trying to loop and concatenate csv column values
My input is
and expected output is
can somebody help me how to loop the column values to get the expected output and thanks in advance.
Basically, you need to read the CSV file line-by-line, store parsed data in array, and then do some nested loops.
This code will do the job for your example (only works for 3 columns):
<?php
$rows = [];
$file = fopen("your-file.csv", "r"); // open your file
while (!feof($file)) { // read file till the end
$row = fgetcsv($file); // get current row as an array of elements
if (!empty($row)) { // check that it's not the empty row
array_push($rows, $row); // store row in array
}
}
fclose($file);
for ($r1 = 0; $r1 < count($rows); $r1++) {
for ($r2 = 0; $r2 < count($rows); $r2++) {
for ($r3 = 0; $r3 < count($rows); $r3++) {
echo $rows[$r1][0] . '_' . $rows[$r2][1] . '_' . $rows[$r3][2] . PHP_EOL;
}
}
}
It's pretty dirty solution, I hope that you can make it cleaner, using recursion, instead of nested loops in case if you need to parse unknown columns count.
If you have another fixed number of columns, just add more nested loops (for $r4, $r5, and so on).
More info about how to read CSV file in PHP on w3schools.com
Documentation about join() function, which is alias of implode() function on php.net

Array push rows from SQL query

I am trying to save the rows (results) from an SQL query to a csv file.
I am using array push in order to put the results in a list. Later I put the data from this list to my csv file.
My code :
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list, $row['campaign']);
}
The results are there because sprintf works. The problem is with the syntax of array_push. I even tried :
array_push($list, array(''.$row['campaign']);
I am getting an error:
fputcsv() expects parameter 2 to be array
The full code is here :
$list = array
(
array('old_campaign_name', 'new_campaign_name')
);
// table 1
$sql = ('select distinct(campaign) as campaign from '.$table1.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list,$row['campaign'],'');
}
$fp = fopen($location, 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
As the error says, fputcsv expects each row that you put to be an array, so it can write it out with commas separating the elements. $list should be a 2-dimensional array, so you need to push an array onto it when you're building it.
while ($row = $query->fetch_assoc() {
$list[] = array($row['campaign']);
}
BTW, $list[] = x is equivalent to array_push($list, x).
When you initially create the $list array, it is an array containing one array. But when you add more values to it from your query results, you are pushing strings onto the end of it, not arrays. In effect, you will be making something like
$list = array (
array('old_campaign_name', 'new_campaign_name'),
'first campaign',
'second campaign',
'etc.',
...
);
Because of this, when you loop over $list, the first value should work with fputcsv, because it is an array, but any subsequent values will be strings instead of arrays and will cause the error you are seeing.
You should be able to fill the $list like this:
while ($row = $query->fetch_assoc()) {
$list[] = $row;
}
$list[] = $row will not overwrite the values previously in $list. From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
It works like this :
while ($row = $query->fetch_assoc())
{
// array_push($list,$row['campaign'],'');
array_push($list,array($row['campaign'], ''));
}

PHP Implode returning single entry

I'm trying to use implode() in a script to return the result of an SQL query as a string so I can insert it into another table, however whenever I manage to get the implode to return anything it will only return a single result, even though the query returns more than one result.
Note: my PHP is not the strongest and I am using pre-existing code and reworking it, which is why a lot of the code will look like it's meant for a JSON API.
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Events Scheduled!";
$response["events"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["id"];
$post["message"] = $row["message"];
$post["pin"] = $row["pin"];
array_push($response["events"], $post);
$matstring=implode("', '",$post);
}
}
When echo'd out I get:
3', 'Test to check multiple entries are in array for when the check is made, this should be seen.', '12345
imploding $response['events'] returns "Array, Array" and everything else I have tried returns nothing. Where should I look to get the other entry?
I think what are you want is like this:
$str = "'".implode(",'", $post)."'";
echo $str;

PHP: foreach msqli_query issue

I'm having an odd issue with a small piece of code right now. I've blown too much time trying to figure it out, so I figured I'd ask here. I have an array of integers ($childIDs) that I want to use to call individually on a stored procedure in a MySQL database. The connection is set up fine and this structure hasn't given me any problems until now.
The $childIDs array is set up properly, and the foreach loop does loop through each integer in the array as $currentChild. I first noticed that only the first item in the array would show up. After some testing, I found that $result was being set to a bool(false) after the first iteration of the loop. That being said, the query works fine with the numbers I'm using in the array.
So my question is why $result = mysqli_query($database, "CALL get_notes($currentChild);") is a false bool on everything but the first iteration of the foreach loop?
Here's the code:
$childIDs = array();
$childIDs = json_decode($_GET['childids']);
$noteList = array();
foreach ($childIDs as $currentChild)
{
if ($result = mysqli_query($database, "CALL get_notes($currentChild);"))
{
// Gathers all the notes for the child
while($row = mysqli_fetch_array($result))
{
// does stuff with each row, for now I'll just use an example...
var_dump($row);
}
}
}
This is solved by mysqli_next_result(). I needed to free up mysqli before every new iteration that called mysql_query(). Here's the working code:
$childIDs = array();
$childIDs = json_decode($_GET['childids']);
$noteList = array();
foreach ($childIDs as $currentChild)
{
if ($result = mysqli_query($database, "CALL get_notes($currentChild);"))
{
// Gathers all the notes for the child
while($row = mysqli_fetch_array($result))
{
// does stuff with each row, for now I'll just use an example...
var_dump($row);
}
}
mysqli_next_result($database);
}

Reading a txt file in php and parsing the data to MySQL

im new to php and i hope you can help with an easy to get script. I have a txt file with this general format:
5TB-2A, L+, 1, 1695, 3255, l.jpg
5TB-2A, L-, 2, 1965, 3270, l.jpg
5TB-2A, D-, 7, 2970, 3270, l.jpg
5TB-2A, DFOK, 8, 3225, 3300, l.jpg
I want to read this txt file using php to retrive every data separated by "," into my MySQL table. Thanks for any help.
$lines=file($yourTxt);
foreach($lines as $v) {
$values = explode(',',$v);
PDO::prepare("INSERT INTO tbl (?,?,?,?,?)");
PDO::execute($values);
}
You can make a further check too see if the line just read is ok like:
foreach($lines as $v) {
$values = explode(',',$v);
if (count($values)!=6)
continue;
}
You could use fgetcsv (http://php.net/fgetcsv) to read the file into an array in PHP and then write a query to insert it into the table one row at a time.
<?php
$results = array();
$rows = file($filename, FILE_SKIP_EMPTY_LINES);
if(empty($rows)){
// no data to parse
} else{
foreach($rows as $row){
$values = explode(', ', $row);
// keep only those values which have the 5 variables
if(count($values) > 5){
$results[] = $values;
}
}
}
// see if we have the correct data
print_r($results);
// ... then do your db inserts here
?>

Categories