PHP - Write A Loop To A File
Got a little stuck here.
I'm trying to format an existing .txt file, format it and then write it to .sql file. Here's my code: Code: [Select] $handle = @fopen("nations.txt", "r"); if ($handle) { while (($buffer = fgets($handle, 1024)) !== false) { $column = explode("|",$buffer); // format file $myFile = "nation_dump_".date("Y-m-d").".sql"; // create file $fh = fopen($myFile, 'w') or die("can't open file"); foreach($column as $col) { fwrite($fh, $col[0]); //write the first broken segment from explode() to file } fclose($fh); } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); } The error is on this line, within the foreach loop. fwrite($fh, $col[0]); When I removed the index it only wrote the last line to the file, but I want it to loop through all the lines.. What am I doing wrong here? Similar TutorialsCode: [Select] //this varible contains the array of existing users $existing_users=array('roshan','mike','jason'); //value got from the get metho $user_name=$_POST['user_name']; //checking weather user exists or not in $existing_users array if (in_array($user_name, $existing_users)) { //user name is not available echo "no"; } else { //username available i.e. user name doesn't exists in array echo "yes"; } the array near the top has a list of users, I would like to loop through my users in my database I know how to write a loop but not into here Code: [Select] $existing_users=array('roshan','mike','jason'); I get the error: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\mypubspace.com\wwwroot\phpsite\pubs.php on line 95 Code: [Select] $towns = "SELECT DISTINCT rsTown, COUNT(PubID) As PubCount FROM pubs GROUP BY rsTown ORDER BY rsTown ASC"; $townresult = mysql_query($towns) or die(mysql_error().'<br>SQL: ' . $towns); echo <<<EOF <form name="form3" method="post" action=""> <select name="menu2" onChange="MM_jumpMenu('parent',this,0)" class="textbox"> <option value="">Please choose a town!</option> while($row1 = mysql_fetch_array($townresult)){ <option value="pubs_norm1.asp?rsTown='$row1['RSTOWN'];'"> Pubs and bars in $row1['RSTOWN']; ($row1['RSTOWN'];)</option> } </select> </form> EOF; Please help Hi All, Can any body let me know what is proper way to write below code? Quote while($row = mysql_fetch_array($result)) { for ($colq=0; $colq<=$col_no;$colq++) { while($col = mysql_fetch_array($result_display_sequences)) { for ($b=0; $b<=$seq_num;$b++) { echo $col[$b] . " "; while($asso = mysql_fetch_array($result_column_associated)) { for ($c=0; $c<=$asso_num;$c++) { echo $asso[$c] . " "; if ($col[$b] == $asso[$c]) { echo "<td>" . $row[$colq] . "</td>"; } } } } } } } I want to match two values before display the result but somehow at first level its work perfect but then its didnt increase value $b as it should. So i lil but confuse now what am i doing wrong with it. Sorry i am new and trying something hard assignment while test my skill. i do get result as below 2 2 3 4 5 6 7 8 9 10 11 3 4 5 6 7 8 9 10 11 Thanks in Advance. I need some help...I want to read the contents of a file into a variable and then insert/write that content into another file. Code: [Select] $handle = fopen($create_mysql_db_url, "rb"); $contents = fread($handle, filesize($create_mysql_db_url)); fclose($handle); $userFileName = $_POST['mysqluser'] . time() . ".php.txt"; $fhandle = fopen($userFileName,"wb"); fwrite($fhandle, $contents); fclose($fhandle); $fh = fopen($userFileName,"wb"); $contents = fread($fh, filesize($userFileName)); $content = preg_replace("/###USERNAME###/", $_POST['mysqluser'], $contents); $content = preg_replace("/###PASSWORD###/", $_POST['mysqlpass'], $content); fwrite($fh, $content); fclose($fh); please help Why doesn't it add a new line when I open up index.php Code: [Select] $fp = fopen('text.txt','w'); fwrite($fp, "Your IP: ".$_SERVER['REMOTE_ADDR']."\n"); fclose($fp); I produce a series of php variables in a php strict (mostly come from mysql), and I want to save them as a php file. To be use for "include". What is the safest way to write them in a php file? I tried to save them in the manner of saving a text file with fwrite as Code: [Select] $data='<?php $cat=array('array created in the text'); $string='some value';?>'; $fh = fopen("file.php", 'w'); fwrite($fh, $data); Now, file.php is a normal php file and I can call it with "include"; but the problem is that this method is not safe. For example, if the string is "There's something", php gives error for the presence of ' in the string. I can skip ' and " by backslash; but this method is costy, as I need to perform this process for all strings to be saved. Moreover, there might be other source of errors too (that I have not encountered yet). Is there a safe way for writing a php code to file? <?php $a = 2; $b = 3; $z = fopen("test.txt", 'a+'); if($a > $b) { echo "A is bigger than B"; } elseif fwrite($z, $b); fclose($z); ?> is there a way to get elseif to write to a file? so if b is bigger than a it writes $b to a file? eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. Hi All, I am presently using a Debian VPS to which, if I need, I can add another disk. In my website, users can upload images, that are then stored in the primary disk into a child directory of a directory called httpdocs. Instead of the primary disk, would it be possible to have them stored in a secondary disk ? I am asking this because I am not sure that a user connected to my website is allowed to run a PHP script intended to write a file in a directory that actually does not belong to the httpdocs directory. Thanks Hello Everyone, I'm new to PHP and got a good big stuff. I would like to write an image in excel file. There will be almost 600+ rows and each row will have url and qrcode image. I would like to write an excel file which will write url and respective image into the next cell of the url. Is it possible to write an image in excel file? If yes, can anyone please guide me how? I have read so many post saying to use a pear package but again pear package is not allowing to write jpe/gif it only allows .bmp files. So, pear package is I don't think will work for me. I have also attached an example excel file which is showing the way I require to have an output. Please anyone if having any idea guide me and let me know. Thank you in advance for your help. Looking forward to hear from you soon! I very new to php and all I am simply trying to do is read the contents of a text file and echo it out on the screen. I have tried many things to see what I am doing wrong but it just simply isnt working for me. I know the server I am using has php enabled as well because I have tried a simple echo and it works fine. This is the code I am currently using. <?php $file = fopen(file.txt", 'r'); $read = fread($file, '6') echo $read; ?> also, I have tried this. <?php $file = file_get_contents('file.txt'); echo $file; ?> I have a file.txt on the server I am using in the same directory as index.php, I feel like this should be working but I get no result! Alls I have in the text file is a statement that says "hello world". Ok, so I have an INI file... OLD HTML= NEW HTML= I need to write the contents $oldhtml to "OLD HTML=" and the contents of $newhtml to "NEW HTML=" To store the contents of an ini file to a variable, I just used Code: [Select] $config = parse_ini_file("config.ini",1); $email = $config['Email']; $host = $config['Host']; Cant I just write to the file by selecting ['Old HTML'] and ['NEW HTML'], in a fashion similar to the above code? I am trying to write post variables to a csv file but it writes everything in one line separated by comma <?php $list= array($_POST['purchases']); $file = fopen("purchases.csv", "w"); foreach ($list as $line) { fputcsv($file, $line); } fclose($file); ?> Result in purchases.csv file Marilyn,Nancy,Johan,Carol,Juanic,Shirley But I want every string value on separated line Marilyn Nancy Johan Carol Juanic Shirley
Just trying to create a simple form that will let you enter a message that will get written to a text file. Code for SetMessage.php: Code: [Select] <?php if($_SERVER['REQUEST_METHOD'] != 'POST') { ?> <form method="POST" action="setmessage.php" name="setmessage"> <p>Message to Display:<Input type="text" name="message" size="50"></p> <p><input type="submit" value="Submit" name="submit"></p> </form> <?php } else { //Writes the contents of the message to a file echo file_put_contents('message.txt', $_POST['message']); } ?> When submitting, I get the error "Call to undefined function: file_put_contents() on line 16" Is there a way to write a file to a directory on my network? I tried creating a shortcut called automated and pointed it to the network path. I also set up a virtual directory called automated in IIS and still could not make it work. I gave it read and write permissions. error Warning: fopen(C:\Inetpub\wwwroot\dompdf\automated\resource.pdf) [function.fopen]: failed to open stream: No such file or directory in C:\Inetpub\wwwroot\date.php on line 69 Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\Inetpub\wwwroot\date.php on line 70 Warning: fclose() expects parameter 1 to be resource, boolean given in C:\Inetpub\wwwroot\date.php on line 71 code Code: [Select] require_once("dompdf/dompdf_config.inc.php"); $html = '<html><body>'. '<p>Put your html here, or generate it with your favourite '. 'templating system.</p>'. '</body></html>'; $dompdf = new DOMPDF(); $dompdf->load_html($html); $dompdf->render(); $pdfoutput = $dompdf->output(); $filename = "C:\\Inetpub\\wwwroot\\dompdf\\automated\\resource.pdf"; $fp = fopen($filename, "a"); fwrite($fp, $pdfoutput); fclose($fp); I append a string to a file by fwrite as Code: [Select] $str= 'dynamic text from each run'; $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "$str\n"; fwrite($fh, $stringData); fclose($fh); but I want to avoid duplicate to keep the file small. I want to avoid writing if the term is already saved in the file. I want to have a file containing unique lines. I'm trying to include a routine to catch an error but it doesn't seem to write to a text file within a function. just using the following simple code, even if I simply try to write a letter it doesn't work
if ($http_status == 200) { return $response; } else { $myfile = fopen("ErrorData.txt", "a+") or die("Unable to open file!"); $txt = date("H:i:sa d-m-Y")." / Error data- / ".json_encode($response)."\r\n"; fwrite($myfile, $txt); fclose($myfile); }
Edited September 13, 2019 by Dvae56 Added code Hi, I want to read image file and write in to word document file using php. Actually i am developing shopping cart site. for that i have created barcode image. i need to take print outs. for example if i click print means same barcode should be generate 64 times in word document. how i do it? i have tried with COM. please check the following code <?php // starting word $word = new COM("word.application") or die("Unable to instantiate Word"); echo "Loaded Word, version {$word->Version}\n"; //bring it to front $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff for($i=1;$i<=64;$i++) { $word->Selection->InlineShapes->AddPicture("D:\Program Files\wamp\www\b.jpg ",false, True); } $word->Documents[1]->SaveAs("D:\Program Files\wamp\www\Uselesstest.doc"); //closing word $word->Quit(); //free the object $word = null; ?> It works fine in local. but it is not working in server (it says COM.class is missing). i have checked some forums they said it works with MS based operation system. i have checked with windows only. Please kindly any one help me asap the way for read and write image file in word document. can we do this any other way? we are reading and writing txt files using php the same can we do with image file (read and write in word document) ?? Thanks Prema Hey there, Thanks for taking the time to read my thread, well basically I'm in a bit of a dilemma. I've got a string in PHP containing the contents of a file I would like to be created and I have a method of sending the command to the remote server like so: $Connection->exec('ps aux'); Now my issue is I am unaware of any file editors via command like that don't have some sort of user prompt I've scoured Google for hours searching for the best possible method for this but all the file editors aren't simply processed by one line commands and edited in that same command e.g Create File -> Write File -> Close File Is there no possible means of doing that via one line command?. Here is my string I wish to be written to the file. $RestartFile = "#!/bin/bash export SERVER_PATH=/home/client".$Server['server_owner']."/".$Server['server_id']." cd $SERVER_PATH while [ true ]; do ./server".$Server['server_id']." & done"); Thank you for your time. Is this the correct way to write binary data to a file? $string = 'this is a string'; $handle = fopen('b.dat', 'wb'); for($i=0;$i<strlen($string);$i++){ $hx = bin2hex($string{$i}); fwrite($handle, pack("H*", $hx)); } If so, how do I read it an convert it back to a string? If it is not correct, how do I do it? |