PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hi another question for the php guru's here. I am trying to write program that opens a serialized text file and either takes out certain words (this I would prefer) of at least replaces them with " ". It is not working to well. Here is what I have generally:
<? php
$eraseData = array(
'name' => " ",
'cart' => " ",
'date' => " "
);
$file = file("carts.txt"); //get the file as an array
foreach($file as $line)
{
$myline = trim($line); //remove any spaces
$current_cart = unserialize($myline); //unserialize the string and get the stored cart array
$switch_text_file = str_replace($current_cart,$eraseData,$current_cart); //make the replacement
//open text file and switch out reservation info with $eraseData
$cart_string = serialize($switch_text_file);
$fp = fopen("carts.txt","a");// append does not make sense here would write be better?
fwrite($fp,$cart_string);
fclose($fp);
}
As always, thank you so much for your help and your patience. I have learned so much from this forum in the last week that it is really hard to believe (of course this forum also emphasizes how much more I need to learn).
Firstly, you would need to take a look at how str_replace() works, the first argument should be the words you're looking for, the second is what you want to replace these with and the third is the what needs words replaced. Therefor for the first argument you actually need an array of the words to be replaced, in this case you can grab it using array_keys() on the $eraseData array.
<? php
$eraseData = array(
'name' => " ",
'cart' => " ",
'date' => " "
);
$file = file("carts.txt"); //get the file as an array
foreach($file as $line)
{
$myline = trim($line); //remove any spaces
$current_cart = unserialize($myline); //unserialize the string and get the stored cart array
$switch_text_file = str_replace($current_cart,$erase_data,$current_cart); //make the replacement
/* so looking above I want to replace the data in the arrary $current_cart with the data in the arary $erase_data.
then I want to put those changes back into the text file. But I am assuming since the only thing that is in a
format that can be used (unserialized) is $current_cart that I would need to put the changes back into $current_cart.
the only thing I am not sure about here is what actually needs to be replaced. Meaning is the third part of this
function supposed to be $current_cart or $file (which is serialized and would probably need to be unserialized before
changes took place */
}
Also, when I am finished doing the switch and want to write to the text file. Do I append the data or just rewrite the whole file? In other words do I use ("w" or "a") or should I use some other method to write to the text file?