Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to update a specific line in a textfile using PHP?
    text
    copied!<p>Just need a little help here about my problem. I am trying to create a simple update in a textfile. </p> <p>My goal is:</p> <ol> <li>If the data is existed in the textfile. Don't add a new line in the file instead update that certain line.</li> <li>If data is not existed simple add a new line in the file.</li> </ol> <p>I have a problem in updating. I used the array_replace() function to do this but it always add a new line. My updates are always appending to the textfiles.</p> <p>Here's my code I hope that you can help me.</p> <pre><code>//This is the new array from the user $data_add = array( 'restaurant_id' =&gt; $restaurant_id, 'new_lat' =&gt; $new_lat_entry, 'new_long' =&gt; $new_long_entry, 'date_updated' =&gt; date('Y-m-d H:i:s') ); //This is the base array - It will get the text file if exsited $data = unserialize(file_get_contents('addresses.txt')); //get the ID of the new array - use for validation $target = $data_add['restaurant_id']; //loop the abase array for ($i = 0; $i &lt; count($data); $i++) { //get the ID of the base array $get_id = $data[$i]['restaurant_id']; //compare base array ID and new array ID if($get_id == $target){ // IF FOUND IN THE TEXTFILE $add_data = array(); $add_data = array( $i =&gt; $data_add ); //replace the existed array in textfile with my updated array $new_array = array(); $new_array = array_replace($data,$add_data); //break; }else{ //IF NOT FOUND, SIMPLY ADD $new_array = array( $i =&gt; $data_add ); //fn_print_die($new_array); } } //FOR DISPLAYING PURPOSES echo "&lt;pre&gt;"; echo "BASE ARRAY&lt;br /&gt;"; print_r($data); echo "---------------------------------------------------------&lt;br /&gt;"; echo "NEW ARRAY&lt;br /&gt;"; print_r($add_data); echo "---------------------------------------------------------&lt;br /&gt;"; echo "REPLACED ARRAY&lt;br /&gt;"; print_r($new_array); echo "---------------------------------------------------------&lt;br /&gt;"; //exit; //SERIALIZE THE UPDATED ARRAY $serialize_data = serialize($new_array); //WRITE THE TEXTFILE $file_input_txt = fopen("addresses.txt","a+"); fwrite($file_input_txt,$serialize_data); fclose($file_input_txt); //exit; $array = unserialize(file_get_contents('addresses.txt')); $file_input = fopen("addresses.csv","a+"); fputcsv($file_input, $data_add); fclose($file_input); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload