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

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

Related

How to echo array elements that contain a variable —PHP

I have a script that looks through a file and returns every newline as an array element.
$file = fopen("dict.txt", "r");
$entries = array();
while (!feof($file)) { $entries[] = fgets($file); }
fclose($file);
I also have a script which does some utilities with a $_GET variable.
$word = htmlspecialchars($_GET["user"]);
$letters = $word[0] . $word[1] . $word[2];
What I would like to do now is to echo all elements in the $entries array beginning with $letters.
Any help would be much appreciated.
try
foreach($entries as $entry) {
if (strpos($entry, $letters) === 0) {
echo $entry;
}
}

php to convert CSV to JSON with nested objects

I have csv file like this:
data,IF,VVS1,VVS2
D,23,17,15
E,17,15,14
What i need is to convert this CSV into JSON but to look like this:
{"D" : {"IF":"23", "VVS1":"17", "VVS2":"15"},"E" : {"IF":"17", "VVS1":"15", "VVS2":"14"}}
Any help?
/* Lets suppose, the csv file is, mydata.scv */
<?php
$mydata = array();
if($file = fopen("mydata.csv","r")){
$csvheaders = fgetcsv($file);
while(($row = fgetcsv($file)) !== FALSE){
$arr = array();
for($i=1; $i<count($csvheaders); $i++){
$arr[$csvheaders[$i]] = $row[$i];
}
$mydata[$row[0]] = $arr;
}
fclose($file);
// encode $mydata array into json to get result in the required format
$mydatainformat = json_encode($mydata);
echo $mydatainformat; // This is your output.
}
?>
Maybe help you, but I recommend add error handling.
<?php
$file = fopen('test.csv', 'r');
$header = fgetcsv($file);
array_shift($header);
$data = array();
while ($row = fgetcsv($file))
{
$key = array_shift($row);
$data[$key] = array_combine($header, $row);
}
echo json_encode($data);
fclose($file);

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.

invalid arguments foreach in php in commandline

I wrote a script in php which reads two files and takes all the strings from one file and searches them in other file. This is working fine in web browser. But when I try to run it through command line, it says
'invalid arguments supplied for foreach() at line....'
am I missing anything?
<?php
$filename = 'search_items.txt';
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode(",", fread($fp, filesize($filename)));
}
$filename1 = 'file1.log';
$fp1 = #fopen($filename1, 'r');
if ($fp1) {
$array1 = explode("\n", fread($fp1, filesize($filename1)));
}
$num = 1;
foreach($array1 as $val1){
foreach($array as $val){
if(strstr($val1, $val)){
echo 'line : '.$num.'->'.$val1.'<br>';
}
}
++$num;
}
?>
<?php
$filename = 'search_items.txt';
$fp = fopen($filename, 'r');
if ($fp) {
$array = explode(",", fread($fp, filesize($filename)));
}
$filename1 = 'file1.log';
$fp1 = fopen($filename1, 'r');
if ($fp1) {
$array1 = explode("\n", fread($fp1, filesize($filename1)));
}
$num = 1;
foreach($array1 as $val1)
{
foreach($array as $val)
{
if(strstr($val1, $val))
{
print_r('\n'); //2
}
}
++$num;
print_r($val1); // 1
}
Ok, the script is running now, but with something funny going on.
if I remove the print in comment 1 and place it in comment 2 place, the results I am getting is the last result , i.e just one last result. not the full searches. Can anyone tell me why?
Your fopen calls are not finding their file, I imagine. First, remove the '#' from '#fopen', so you can see it fail. Then, do this:
$filename = dirname(__FILE__).'/search_items.txt';
//...
$filename1 = dirname(__FILE__).'/file1.log';
That will keep your file locations straight.
Probably your file paths are off, so $array and $array1 are never created. Relative paths will be from where you call the script, not the location of the script.
Maybe variables are empty or not exist?
$array = $array1 = array();
//...
foreach((array)$array1 as $val1)
{
foreach((array)$array as $val)
{
if(strstr($val1, $val))
{
echo 'line : '.$num.'->'.$val1.'<br>';
}
}
$num++;
}
To be on the safe side you should add a check if the file pointers are valid before running the foreach loops, or throw some errors if you fail to open a file.
<?php
$filename = 'search_items.txt';
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode(",", fread($fp, filesize($filename)));
}
$filename1 = 'file1.log';
$fp1 = #fopen($filename1, 'r');
if ($fp1) {
$array1 = explode("\n", fread($fp1, filesize($filename1)));
}
$num = 1;
if($fp && $fp1)
{
foreach($array1 as $val1)
{
foreach($array as $val)
{
if(strstr($val1, $val))
{
echo 'line : '.$num.'->'.$val1.'<br>';
}
}
++$num;
}
}
?>
Keep in mind that when running a script from CLI, the current directory is the directory from which the script was started. When running trough Apache, the current directory is the directory of the script. This bit me a couple of times.

Categories