invalid argument when imploding in php - php

Im getting invalid argument error when running the following code. Im trying to change the value of a line in the $info array, then implode it, implode its parent array, and then save the whole shebang back to whence it came.
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i = $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$presave = implode("%%", $info);
}
}
$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
update below
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$target = $_GET['target'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i == $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$csvpre[$key] = implode("%%", $info);
}
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
Target is the field within the selected Row that i wish to update with the newfieldvalue data.

$save = implode("###", $presave);
At that point, $presave is a string, and should be an array to work with implode. Create an array where you push the $presave-values, and implode that one.

$presave contains the last processed line (i.e. a string) and implode expects an array. To store the line back in the original array, change:
$presave = implode("%%", $info);
to:
$csvpre[$key] = implode("%%", $info);
And to convert the whole CSV array into a string, change:
$save = implode("###", $presave);
to:
$save = implode("###", $csvpre);
And one more problem:
if($i = $row){
should be:
if($i == $row){
because you want to compare the variables, not assign $i.

Related

Append brackets at the end in the CSV file

At the beginning and at ending of the contents I have to append the brackets my csv file looks like this
date1,success,failure,count
1427653800,95,65,160
1427653800,30,10,40
1427740200,10,8,18
1427740200,30,38,68
1427826600,38,20,58
1427826600,60,10,70
1427653800,15,15,30
1427653800,10,10,20
After adding brackets the contents should look like this: [1427653800,95,65,160]
My php code is below:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, $row);
}
fclose($fp);
?>
this is my conn.php file ,please suggest me on this
it is better to use this query
$sql = "SELECT CONCAT('[','',(SUBSTRING(UNIX_TIMESTAMP(date1),1,10))),success,failure,CONCAT(count,'',']') from h_statistics";
it give you result like [1427653800,95,65,160] so no need to do any code in you while loop
Try to append and prepend the brackets :
$row[0] = '['.$row[0];
$row[3] .= ']';
fputcsv($fp, $row);
try with my function which is adding your text to the first and last element of the associative array:
<?php
function array_brackets($array,$prefix,$suffix){
//add prefix to the first element
end($array);
$key = key($array);
$array[$key] = $prefix . $array[$key];
//add sufix to the last element
reset($array);
$key = key($array);
$array[$key] = $array[$key] . $suffix;
return $array;
}
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, array_brackets($row,"[","]"));
}
fclose($fp);
?>
Please run this code and give me the output:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
//$fp = fopen("data.csv", "w");
//fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
//fputcsv($fp, array_brackets($row,"[","]"));
print_r($row);
exit;
}
//fclose($fp);
?>

PHP Undefined Offset with fgetcsv

Okay, I've spent several hours on this problem and I'm not sure what's going on. I think I just need a fresh perspective on this problem especially since I've been up for over 24 hours and the deadline for this is in five hours.
I am getting an Undefined offset notice for every single offset (0 to 907) when I try to use the data I pulled from a CSV. (It probably means I am not successfully pulling the data, but I am exhausted and would appreciate some help)
Does anyone know what I'm doing wrong?
$lines = array();
$lines2 = "";
$one = array();
$two = array();
$three = array();
$four = array();
$five = array();
$six = array();
$header = "";
$footer = "";
$countLines = 0;
/*
* Open the file and store its data into an array
*/
$fp = fopen('db.csv','r') or die("can't open file");
while($lines = fgetcsv($fp)) {
for ($k = 0, $m = count($lines) - 1; $k < $m; $k++) {
$one[$k] = $lines[0];
$two[$k] = $lines[1];
$three[$k] = $lines[2];
$four[$k] = $lines[3];
$five[$k] = $lines[4];
$six[$k] = $lines[5];
}
$countLines++;
}
fclose($fp) or die("can't close file");
/*
* Set up file header
*/
$header = "Header"
;
/*
* Set up file footer
*/
$footer = "Footer";
/*
* Prepare data for export
*/
for ($i = 0, $j = $countLines - 1; $i < $j; $i++) {
$lines2 .= $one[$i] ." ".
$two[$i] ." ".
str_pad($three[$i], 3) ." ".
str_pad($four[$i], 30) ." ".
str_pad($five[$i], 30) ." ".
str_pad($six[$i], 30) ."\r\n";
}
/*
* Store data in file
*/
$fp = fopen('db2.csv', 'w') or die("can't open file");
fwrite($fp, $header);
fwrite($fp, $lines2);
fwrite($fp, $footer);
fclose($fp) or die("can't close file");
The CSV file is a standard comma-delimited file so I don't see any reason to post that data here.
The statement
while($lines = fgetcsv($fp)) {
fgetcsv will return a single line in the form of an array containing the elements on the line;
Therefore the following is wrong and needs to be removed as you are iterating over a single line in the CSV
for ($k = 0, $m = count($lines) - 1; $k < $m; $k++) {
So, after revision the reading loop should (I think) be like this:
$fp = fopen('db.csv','r') or die("can't open file");
$k=0;
while($lines = fgetcsv($fp)) {
$one[$k] = $lines[0];
$two[$k] = $lines[1];
$three[$k] = $lines[2];
$four[$k] = $lines[3];
$five[$k] = $lines[4];
$six[$k] = $lines[5];
$k++;
$countLines++;
}
After this use, e.g. print_r($one) for debug to view the arrays.
To output it I'm relying heavily on guesswork as to what you want to achieve, because you are outputting to db2.csv, but without commas (to seperate). however try something like the following
/*
* Store data in file
*/
$fp = fopen('db2.csv', 'w') or die("can't open file");
fwrite($fp, $header);
/*
* Data for export
*/
for ($i = 0, $j = $countLines - 1; $i < $j; $i++) {
fprintf($fp, "%s %s %-3s %-30s %-30s %-30s\r\n", /* possibly add commas here? */
$one[$i], $two[$i], $three[$i],$four[$i], $five[$i], $six[$i]);
}
I get the same one and look for a solution as you ...
In fact it's really simple and diabolic :fgetcsv() add an array with one NULL value at the end of the reading. Therefore, $lines[1] will produce an error, because the last added array has only one value.
Just count the number of columns in $lines like this :
/*
* Open the file and store its data into an array
*/
$fp = fopen('db.csv','r') or die("can't open file");
while($lines = fgetcsv($fp)) {
if ( count($lines) == 6 )
{
for ($k = 0, $m = count($lines) - 1; $k < $m; $k++) {
$one[$k] = $lines[0];
$two[$k] = $lines[1];
$three[$k] = $lines[2];
$four[$k] = $lines[3];
$five[$k] = $lines[4];
$six[$k] = $lines[5];
}
}
$countLines++;
}

PHP : POST-- How to replace defined KEY from ARRAY in a file

I'm a bit lost for I'm "green" in PHP.
Please, may you teach me how to fix this:
on 'POST' --> Replace a specified array key from a file:
(WRONG:)
<?php
$newData = $_POST["sendData"];
if(isset($_POST['sendData'])){
$file = fopen('fileToOpen.php', 'a');
foreach($file as $key => $val)
{
$data[$key] = explode("|", $val);
}
for($k = 0; $k < sizeof($file); $k++)
{
unset($data[$k][3]);
}
$data[$k][3] = "$newData";
fwrite($file, $data[$k][3]);
fclose ($file);
}
?>
That's wrong as it continues to write:
data1|data2|data3|oldDatanewData
instead of rewrite:
data1|data2|data3|newData
Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?
Thanks!
Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.
$data_array = unserialize(file_get_contents('fileToOpen.php'));
$data_array[$key_you_want_to_change] = $new_data;
file_put_contents('fileToOpen.php', serialize($data_array));
$newData = $_POST['sendData'];
if(isset($_POST['sendData'])){
$file = "fileToOpen.php";
$oldData = file_get_contents($file);
$oldData = eregi_replace("\n","",$oldData);
$FullDataArray = explode("?",$oldData);
$oldDataArray = explode("|",$FullDataArray[1]);
$oldDataArray[3] = $newData;
$newDataString .= "
foreach($oldDataArray as $key=>$val) {
$newDataString .= $val;
if($key!="3") {
$newDataString .= "|";
}
}
$fh = fopen($file, 'w');
fwrite($fh,$newDataString);
fclose($fh);
}
?>

How can I parse a CSV into array with first value as key?

So I have a CSV file that looks like this:
12345, Here is some text
20394, Here is some more text
How can I insert this into an array that looks like so
$text = "12345" => "Here is some text",
"20394" => "Here is some more text";
This is what I currently had to get a single numerical based value on a one tier CSV
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r";
$qid = array();
$qid = str_getcsv($csvData, $csvDelim);
} else {
die("Could not open CSV file.");
}
Thanks for the replies, but I still see a potential issue. With these solutions, wouldn't the values store in this way:
$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text
If I tried this on the example csv above, how would the array be structured?
You can use fgetcsv() to read a line from a file into an array. So something like this:
$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
{
$key = array_shift($line);
$a[$key] = $line;
}
fclose($f);
var_dump($a);
Assuming that the first row in the CSV file contains the column headers, this will create an associative array using those headers for each row's data:
$filepath = "./test.csv";
$file = fopen($filepath, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($file)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
print_r($data);
If you are reading a file I can recommend using something like fgetcsv()
This will read each line in the CSV into an array containing all the columns as values.
http://at2.php.net/fgetcsv
$csv_lines = explode('\n',$csv_text);
foreach($csv_lines as $line) {
$csv_array[] = explode(',',$line,1);
}
edit - based on code posted after original question:
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r"; // assume this is the line delim?
$csv_lines = explode($csvDelim,$csvData);
foreach($csv_lines as $line) {
$qid[] = explode(',',$line,1);
}
} else {
die("Could not open CSV file.");
}
With your new file with two columns, $qid should become an array with two values for each line.
$csvDelim = ",";
$qid = str_getcsv($csvData, $csvDelim);
$text[$qid[0]] = $qid[1];

change value of a line in an array

I need to change the value of a line within an array to a given string, then implode and save the data. Im using the code below.
row is the row of the table.
target is the specific line in the array which i want to update.
nfv is the new string i want to put into the array.
<?
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i = $row){
$info = explode("%%", $value);
$j = 0;
foreach ( $info as $key => $value ){
$j++;
if($j == $target){
/*change the value of this line to $newfieldvalue*/
}
}
}
}
$presave = implode("%%", $info);
$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
?>
You do realize that you can index into an array? If you already have the numeric index of an array element, just go ahead and change it:
$arr[$index] = "some new stuff";
Magically updated.

Categories