Hi folks, I wanna know how to use PHP to read write a txt or csv file. In the text file, it should look like the following way: Code: Linktext | http://www.vareside.com/ Other Linktext | http://google.com/ Another Linktext | http://search.yahoo.com/ This should be read and shown in the source code of the PHP file as following: Code: <a href="http://www.vareside.com/">Linktext</a><br> <a href="http://google.com/">Other Linktext</a><br> <a href="http://search.yahoo.com/">Another Linktext</a><br> Then there should be new lines with new linktexts and URL's addable using PHP in the same structure. How to do all that?
Ok here you go first you must change your format a little when adding to the text file use this format. Code: http://www.vareside.com/|Linktextvvl <br> the vvl on the end must be added to each line it will be used by the php file as a trigger/separator. Here is the php code that will write the text file for you the file name will be links.txt It will give you a form to add the links one per line in the format above. Code: <?php $article=$_POST['article']; if (isset($article)) { $myFile = "links.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "$article"; fwrite($fh, $stringData); fclose($fh); header( 'Location: #' ) ; } else { echo"<form action=\"#\" method=\"post\"></td></tr> <tr><td><h3>insert data <br>The vvl after the link title must be used.<br>Enter your links one per line in this format<br>http://www.vareside.com/|Linktextvvl <br></td></tr> <tr><td><textarea name=\"article\" rows=\"20\"cols=\"60\"> </textarea></td></tr><td> <input type=\"submit\" value=\"Insert data\"></form></td></tr></table>"; $myFile = "links.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh,1024); fclose($fh); $Chunks = explode("\n", $theData); for($i = 0; $i < count($Chunks); $i++){ $linkstring = str_replace("http","<a href=\"http",$Chunks[$i]); $linkstring1 = str_replace("|","\">",$linkstring); $linkstring2 = str_replace("vvl","</a>",$linkstring1); echo"$linkstring2<br>\n"; }} ?> And here is the file that will read the text file. and display it as links one per line Code: <?php $myFile = "links.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh,1024); fclose($fh); $Chunks = explode("\n", $theData); for($i = 0; $i < count($Chunks); $i++){ $linkstring = str_replace("http","<a href=\"http",$Chunks[$i]); $linkstring1 = str_replace("|","\">",$linkstring); $linkstring2 = str_replace("vvl","</a>",$linkstring1); echo"$linkstring2<br>\n"; } ?> The first time you call the script it will show an error because the links.txt file does not exist. Just add your first link and after that it will not show the error. Or create a blank file called links.txt in the folder and that will avoid the error also. I put a working copy on my site you can see http://www.bmcoll.com/pagetest/tutorials/filewrite.php Add links play around with it. I will remove it in a few days. Any questions PM me.