PHP - How To Format Text Written To A .txt File ?
Hello everyone,
I'm exporting some mysql data to a text file. The data can be selected by checkboxes from a table. I want to format the text that will be in text file. How do I do that? This is my code: Code: [Select] <?php if ($_POST['exporttxt']) { for($i=0;$i<count($_POST['checkbox']);$i++){ $export_id = $checkbox[$i]; $text = mysql_query("SELECT code FROM tickets WHERE id='$export_id'"); $text = mysql_fetch_assoc($text); $text = $text["code"]; $filename = "export"; $filedate = date("Y-m-d"); $fileext = ".txt"; $fileall = $filename.$filedate.$fileext; ob_end_clean(); header("Content-Type: application/octet-stream"); header("Content-disposition: attachment;filename=\"$fileall\""); header("Content-Type: application/force-download"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: ".strlen($output).";\n"); echo($text); } } exit(); ?> The data that will be exported are numbers containing of 16 digits. After every number I want to have a line-break. Also if possible I would like to have a space after 4 digits for every number, example: Number non-formatted: 1234567891234567 Number formatted: 1234 5678 9123 4567 How can I do that? Similar TutorialsHi All, I am not quite sure if this is possible - but here goes. I have a webpage hit counter that uses PHP and saves the counter totals in .txt files. I have gotten the code to print out the comma (thousand separator) fine on the page, however, I would like to have that comma in the text file also. I display the counters on separate pages using <?php include("file.txt");?> and the counter shows up as "12345" when I'd like it to read the text as "12,345". Basically, I just want that comma written to the actual text file if possible so that when it's included on a web page, it displays the thousands separator. Any help would be great. Thank You! Here is a portion of my code: Code: [Select] /* Turn error notices off */ error_reporting(E_ALL ^ E_NOTICE); /* Get page and log file names */ $page = input($_GET['page']) or die('ERROR: Missing page ID'); $logfile = 'logs/' . $page . '.txt'; /* Does the log exist? */ if (file_exists($logfile)) { /* Get current count */ $count = intval(trim(file_get_contents($logfile))) or $count = 0; $cname = 'tcount_unique_'.$page; if ($count_unique==0 || !isset($_COOKIE[$cname])) { /* Increase the count by 1 */ $count = $count + 1; $fp = @fopen($logfile,'w+') or die('ERROR: Can\'t write to the log file ('.$logfile.'), please make sure this file exists and is CHMOD to 666 (rw-rw-rw-)!'); flock($fp, LOCK_EX); fputs($fp, $count); flock($fp, LOCK_UN); fclose($fp); /* Print the Cookie and P3P compact privacy policy */ header('P3P: CP="NOI NID"'); setcookie($cname, 1, time()+60*60*$unique_hours); } /* Is zero-padding enabled? */ if ($min_digits > 0) { $count = sprintf('%0'.$min_digits.'s',$count); } /* Print out Javascript code and exit */ echo "document.write('".number_format($count)."');"; exit(); } else { die('ERROR: Invalid log file!'); } Hi there, Im working on my little project and I would appreciate your help. I have only basic knowledge of php, mostly I just copy some scripts that could be useful for me. Im trying to find some simple script that allows me to see the written text on web page no. 1 on webpage no. 2.. Something like send the form to email, except I dont want to send it on email, but different webpage. Something like different way of eshop, where you get your order shipped to email, but I wanna send this information to webpage. Is there such a script like Im describing? Probably is but I dont know how to search for this..
Thank You
Edited by Radim, 21 October 2014 - 07:15 AM. Hey everyone, I'm pretty new to this, not my full time job, but just something I thought I'd give a shot... I have a database, in postgres, in which I make my query and I go fetch all the info I need. What I need to do next is the tricky part for me. For each line of results received, I have to output to a text file (.txt) but I have to respect a format that was given to me from the person requesting the info. Example: Character 1 must be G or N. Character 2 to to 11 will be a result from my database search, which is a 10 digit string. Character 12 to 14 must be spaces. Another rule is: start at character 78: input a value from my database search but it must not exceed 20 characters and if it is less then 20 character, fill the remaining with spaces. If anyways has a code I can copy and work off of I would really appreciate it....thanks! death.announcement.contact.php The above file format is correct? thank you I found the following forum topic and have implemented the solution provided at the bottom: http://www.phpfreaks.com/forums/index.php?topic=310258.0 Code: [Select] <?php $cnx = fopen("data/Book1.csv", "r"); //open example.csv echo("<table>\n\t<tbody>\n"); // echo the table while (!feof ($cnx)) { // while not end of file $buffer = fgets($cnx); // get contents of file (name) as variable $values = explode(",", $buffer); //explode "," between the values within the contents echo "\t\t<tr>\n"; for ( $j = 0; $j < count($values); $j++ ) { // echo("\t\t\t<td>$values[$j]</td>\n"); } echo"\t\t</tr>\n"; }; echo("\t</tbody>\n</table>"); fclose($cnx); //close filename variable ?> It works great. One question though - - what might it take to add an if/else statement that inserted the following for the first row in the CSV file ... Code: [Select] echo("\t\t\t<th>$values[$j]</th>\n"); ... and inserted the following for every row after the first ... Code: [Select] echo("\t\t\t<td>$values[$j]</td>\n"); This way I can better control my table through CSS. Any ideas? Hi Guys, I am looking for a way to format excel cells using PHP, I am exporting mysql data to excel file using below method: $fields = array("Date", "Time In", "Time Out", "Hours", "Project", "Component", "Sub-Component", "Work Done", "Supervisor Changes", PHP_EOL); file_put_contents($filename, implode("\t", $fields), FILE_APPEND); Now I want to make BOLD all this header fields, so please help me to this construct.. Thank you Hello, I am designing a site which alows users to upload a certain file type, namely .dem files (gaming demo files). I have tried using mime_content_type(); but it doesn't output anything. I looked at php.net and viewed the example code and tried exactly what they did. As I say, doesn't output anything though. The code is: Code: [Select] <?php echo mime_content_type('smuggles.dem'); ?> I have this code in a file called test.php and the demo file is in the same folder as this file... (wamp/www) php.net states the function is deprecated and advises you to use Fileinfo(). Is this the reason it doesn't work because I was advised from another forum to use the mime_content_type() function. Please if you can help me I would be very grateful. I have been stuck on this for a few days now and have received no more replies from the other forum since my last post. I also thought that coming to a php dominant forum would really help my chances of achieving this. Kind regards, BuNgLe. Hello everyone, What is the best way to take HTML formatted text and overlay it on a image (presumably using php's GD functions)? Unfortunately, HTML tags are ignored and any kind of code is treated as plaintext by imagefttext(). However, I need this HTML DIV box pasted onto an image and I intend to get it done. To make things slightly worst, this is a dynamic, PHP generated DIV box. I had an idea of utilizing some kind of buffering to generate my DIV box, convert that DIV box to an image and finally paste it onto my image using the GD library. If that sounds like a reasonable idea, can someone please help me get started? Thanks in advance, guys! Hello! I have a problem on formatting text witch is being sent by mail. I use this code: Code: [Select] $from = '<someone@example.com>'; $to = 'myemail@mydomain.com'; $message = 'a b c'; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; $headers .= "From: $from" . "\r\n"; mail($to, $subject, $message, $headers); and I'm getting this mail: "a b c" I 've also tried this: Code: [Select] $message = 'a'."\n".' b'."\n".' c'; but i got the same result. As you can see the problem is that i receive amessage that does not contains line brakes. I would be grateful for any kind of help! what I am trying to do is use this php script to load the data being submitted in the html form into my database and then populate the database into an excel (xls) file and then e-mail it to my address. Everything works great it populates into the database and creates the xls file perfect. But it is wanting me to download the file. What can I add to the script to have it e-mail the file to my e-mail address INSTEAD of downloading it. Code: [Select] <?php define('DB_NAME', 'database'); define('DB_USER', 'username'); define('DB_PASSWORD', 'password'); define('DB_HOST', 'hostname'); $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db(DB_NAME, $link); if (!$db_selected) { die('Can\'t use ' . DB_NAME . ': ' . mysql_error()); } $value1 = $_POST['groupname']; $value2 = $_POST['name']; $value3 = $_POST['address']; $value4 = $_POST['city']; $value5 = $_POST['state']; $value6 = $_POST['zip']; $value7 = $_POST['homephone']; $value8 = $_POST['cellphone']; $value9 = $_POST['email']; $value10 = $_POST['age']; $value11 = $_POST['maritalstatus']; $value12 = $_POST['income']; $value13 = $_POST['contact1']; $value14 = $_POST['contact2']; $value15 = $_POST['contact3']; $value16 = $_POST['date1']; $value17 = $_POST['date2']; $value18 = $_POST['date3']; $sql = "INSERT INTO clients (groupname, name, address, city, state, zip, homephone, cellphone, email, age, maritalstatus, income, contact1, contact2, contact3, date1, date2, date3) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9', '$value10', '$value11', '$value12', '$value13', '$value14', '$value15', '$value16', '$value17', '$value18')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } mysql_close(); mysql_connect('hostname', 'username', 'password'); mysql_select_db('database'); $sql = "SELECT `groupname` AS `Group`, `name` AS `Customer Name`, `address` AS `Address`, `city` AS `City`, `state` AS `State`, `zip` AS `Zip Code`, `homephone` AS `Home Phone`, `cellphone` AS `Cell Phone`, `email` AS `E-Mail`, `age` AS `Age Group`, `maritalstatus` AS `Marital Status`, `income` AS `Household Income`, `contact1` AS `Contact VIA`, `contact2` AS `Contact VIA`, `contact3` AS `Contact VIA`, `date1` AS `1st Date`, `date2` AS `2nd Date`, `date3` AS `3rd Date` FROM fundtour_info.clients clients"; // Query Database $result=mysql_query($sql); $filename = 'file.xls'; // Send Header header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download");; header("Content-Disposition: attachment;filename=$filename"); header("Content-Transfer-Encoding: binary "); // XLS Data Cell xlsBOF(); xlsWriteLabel(0,0,"Group"); xlsWriteLabel(0,1,"Name"); xlsWriteLabel(0,2,"Address"); xlsWriteLabel(0,3,"City"); xlsWriteLabel(0,4,"State"); xlsWriteLabel(0,5,"Zip Code"); xlsWriteLabel(0,6,"Home Phone"); xlsWriteLabel(0,7,"Cell Phone"); xlsWriteLabel(0,8,"E-mail Address :"); xlsWriteLabel(0,9,"Age Group"); xlsWriteLabel(0,10,"Marital Status"); xlsWriteLabel(0,11,"Income"); xlsWriteLabel(0,12,"Contact Via"); xlsWriteLabel(0,13,"Dates"); $xlsRow = 1; while(list($groupname,$name,$address,$city,$state,$zip,$homephone,$cellphone,$email,$age,$maritalstatus,$income,$contact1, $contact2, $contact3,$date1, $date3, $date3)=mysql_fetch_row($result)) { ++$i; xlsWriteLabel($xlsRow,0,"$groupname"); xlsWriteLabel($xlsRow,1,"$name"); xlsWriteLabel($xlsRow,2,"$address"); xlsWriteLabel($xlsRow,3,"$city"); xlsWriteLabel($xlsRow,4,"$state"); xlsWriteLabel($xlsRow,5,"$zip"); xlsWriteLabel($xlsRow,6,"$homephone"); xlsWriteLabel($xlsRow,7,"$cellphone"); xlsWriteLabel($xlsRow,8,"$email"); xlsWriteLabel($xlsRow,9,"$age"); xlsWriteLabel($xlsRow,10,"$maritalstatus"); xlsWriteLabel($xlsRow,11,"$income"); xlsWriteLabel($xlsRow,12,"$contact1, $contact2, $contact3"); xlsWriteLabel($xlsRow,13,"$date1, $date3, $date3"); $xlsRow+++; } xlsEOF(); exit(); function xlsBOF() { echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); return; } function xlsEOF() { echo pack("ss", 0x0A, 0x00); return; } function xlsWriteNumber($Row, $Col, $Value) { echo pack("sssss", 0x203, 14, $Row, $Col, 0x0); echo pack("d", $Value); return; } function xlsWriteLabel($Row, $Col, $Value ) { $L = strlen($Value); echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); echo $Value; return; } ?> Thanks for any help I notice that my text gets saved correctly formated in mysql but when I go to display it its not formated anymore. Anyone know what can I do to get it to display correctly? Hi I have the following for an input form, I was under the impression that ucwords would format the text into Initial Characters, but this does not do that? What have I done wrong? $ven_name = trim(ucwords(mysql_prep($_POST['ven_name']))); Hi, In my application I have not used any folders to define the hierarchy. All file s are in a single folder. What is the easy way of creating the Breadcrumb. I am rewriting the URL from www.mysite.com/main.php/page=pagename&id=10 to www.mysite.com/main/pagename/id/10 Is it possible to use the re-written URL to create the breadcrumb? If yes I can define hierarchy in the URL and use the same to create breadcrumb.
Hello All, function convertTimeFormat($time12Hour) { // Initialized required variable to an empty string. $time24Hour = ""; // Used explode() function to break the string into an array and stored its value in $Split variable. $Split = explode(":",$time12Hour); // print_r(explode (":", $time12Hour)); => Array ( [0] => 09 [1] => 50 [2] => 08AM ) // Retrieved only "hour" from the array and stored in $Hour variable. $Hour = $Split[0]; $Split[2] = substr($Split[2],0,2); // Used stripos() function to find the position of the first occurrence of a string inside another string. if($Hour == '12' && strpos($time12Hour,"AM")!== FALSE) { // Code here } elseif(strpos($time12Hour,"PM")!== FALSE && $Hour != "12") { // code here } return $time24Hour; } $time12Hour = "09:50:08AM"; $result = convertTimeFormat($time12Hour); print_r($result); /* Input : "09:50:08AM"; Output : "21:50:08PM"; */
I'm trying to figure out how to create a temporary table of a query join, so I can paginate the results. I kind of made half of this up as i was going along - which is dangerous for a beginner like me. I'm getting this error, and no results on the page: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource on line 179 also, is there a way to combine the two queries (create temp and insert from/into) Code: [Select] $sql2 = "CREATE TEMPORARY TABLE temp_search (plant_id INT PRIMARY KEY AUTO_INCREMENT, scientific_name VARCHAR(75), common_name VARCHAR(75), leaf_shape VARCHAR(75))"; $sqlx = "SELECT descriptors.leaf_shape ,plantae.scientific_name, plantae.common_name FROM descriptors INNER JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE descriptors.leaf_shape LIKE 'auriculate' AND descriptors.leaf_venation LIKE '%$select3%' AND descriptors.leaf_margin LIKE '%$select4%' INTO temp_search (leaf_shape, scientific_name, common_name)"; $sql = "SELECT * FROM temp_search ORDER BY scientific_name ASC LIMIT $start, $limit"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { echo $row['scientific_name'] . $row['common_name'] . $row['leaf_shape'] ; } Hi guys. I have a problem in my web based examanation system written in php. Here's the scenario: when a user takes an exam. 1 question is displayed 1 at a time. my problem is if he/she is at the 2nd question then he/she pressed the back button he/she is redirected back to the 1st question and my system just go crazy. How can i prevent the user from pressing the back button or returning to the previous questions? Please I really need help on this. Can anyone give me suggestion for possible solutions on my problem? Thanks in advance by the way here's my code, you can also download it from attachment. ------------------------------------------process_exam.php------------------------------------------------------------ <?php //start session session_start(); //declare variables //iCorrect= variable for score $_SESSION['iCorrect']=0; //a=variable for iteration kang index kang mga array or serves as an current item number $_SESSION['a']=1; //connect to database include('mysql_connect.php'); $result = mysql_query("select * from questions where exam_id ='$_SESSION[exam_id]'"); //count the number of found questions $_SESSION['num_of_questions']=mysql_num_rows($result); //declare the iterator $i=1; //get the options for the question1,question2 and so on and so on. depende kung ilang questions ang mafetch nya sa dbase.so pde kht ilang questions lagay ng user while ($row = mysql_fetch_assoc($result)) { $questions[$i] = $row['question']; $op1[$i] = $row['op1']; $op2[$i] = $row['op2']; $op3[$i] = $row['op3']; $op4[$i] = $row['op4']; $answers[$i]=$row['answer']; $i++; } //view the data's in the array for debugging purposes echo 'answers: '; print_r($questions); echo '<br>'; print_r($op1); echo '<br>'; print_r($op2); echo '<br>'; print_r($op3); echo '<br>'; print_r($op4); echo '<br>'; print_r($answers); echo '<br>'; echo '<br>'; //pass the arrays to session arrays to be used in other php pages $_SESSION['question']=$questions; $_SESSION['op1']=$op1; $_SESSION['op2']=$op2; $_SESSION['op3']=$op3; $_SESSION['op4']=$op4; $_SESSION['answers']=$answers; //print the arrays. debugging purposes //1 is the starting index of the array because the $i is equal to 1 print_r($_SESSION['question']); echo '<br>'; print_r($_SESSION['op1']); echo '<br>'; print_r($_SESSION['op2']); echo '<br>'; print_r($_SESSION['op3']); echo '<br>'; print_r($_SESSION['op4']); echo '<br>'; print_r($_SESSION['answers']); header("location:exam.php"); ?> </body> </html> ----------------------------------------------------------exam.php-------------------------------------------------------------------- <?php //start session session_start(); echo '<br>'; echo '<br>'; echo '<tr>'; echo '<b>'; echo 'Question: '; echo '<td align = center>'.$_SESSION['question'][$_SESSION['a']].'</td>'; echo '</tr>'; echo '<form method = "post" action= "nxt_question.php">'; echo '<table border = "0">'; echo '<tr>'; //echo '<td>'; echo "<td><Input type =\"Radio\" Name =\"choice\" value='".$_SESSION['op1'][$_SESSION['a']]."'>"; echo '<td>'.$_SESSION['op1'][$_SESSION['a']].'</td>'; echo '</tr>'; echo '<tr>'; echo "<td><Input type =\"Radio\" Name =\"choice\" value='".$_SESSION['op2'][$_SESSION['a']]."'>"; echo '<td>'.$_SESSION['op2'][$_SESSION['a']].'</td>'; echo '</td>'; echo '</tr>'; echo "<td><Input type =\"Radio\" Name =\"choice\" value='".$_SESSION['op3'][$_SESSION['a']]."'>"; echo '<td>'.$_SESSION['op3'][$_SESSION['a']].'</td>'; echo '</tr>'; echo "<td><Input type =\"Radio\" Name =\"choice\" value='".$_SESSION['op4'][$_SESSION['a']]."'>"; echo '<td>'.$_SESSION['op4'][$_SESSION['a']].'</td>'; echo '</tr>'; echo '</table>'; echo '<tr> <td> <input type = "submit" value="Next Question"> </td> </tr>'; echo '</form>'; ?> ----------------------------------------------nxt_question.php------------------------------------- <?php //start session session_start(); //Checking of answers kada mag pindot next question button if(isset($_POST['choice'])) { $ans_of_user=$_POST['choice']; $_SESSION['answers'][$_SESSION['a']]; if (strcmp($ans_of_user,$_SESSION['answers'][$_SESSION['a']])==0) { $_SESSION["iCorrect"]++; } } //add 1 to the session a. session a is the iterator. serves as indexes of the arrays that stores the questions,answers etc... $_SESSION['a']++; //ridirect to exam.php if there are still number of items remaining. while($_SESSION['a']<=$_SESSION['num_of_questions']) { header("location:exam.php"); exit(); //kill the script } echo 'exam finished!'; echo '<br>'; echo 'Your score is: '; echo $_SESSION["iCorrect"]; //unset the session variables needed to be reset unset($_SESSION["iCorrect"]); unset($_SESSION["exam_id"]); unset($_SESSION["invitation_code"]); unset($_SESSION["a"]); unset($_SESSION["num_of_questions"]); unset($_SESSION["question"]); unset($_SESSION["op1"]); unset($_SESSION["op2"]); unset($_SESSION["op3"]); unset($_SESSION["op4"]); unset($_SESSION["answers"]); ?> Hi all, I am currently making a website that has e-custom functions and a back end for the client. I want them to be able to upload images - but they need to be transparent. I do not want to leave this in the hands of the client, so I am looking at ways of using the GD library to make the change I got no issue with the png/gif type for upload/resize function since this type already transparent background but my major problems is how to deal with jpeg/jpg image type which is their background was not a transparent...so is it possible I can change/ convert to png/gif type upon successful of uploading image...so the new final image will be png/gif type with transparent background...is it doable...I am not even sure it is possible...? Thanks for any help.. Hi guys, Should be a simple 1. If i have the following at the top of the page: $page_views = $row['page_views'] + 1; mysql_query("UPDATE table SET page_views='$page_views'"); and then the following at the bottom of the page: echo $row['page_views']; Should I see the page views as 1 the first time the page is visited, 2 the second time the page is visited, and so on......? At the moment im seeing 0 on the first page visit, 1 on the second page visit, 2 on the third..... I had this problem before on another page i was working, and i simply solved it by displaying the mysql query above the echo similar to the code above. However now it does not seem to be working. Am i missing something really simple? lol Thanks Ok i have been working on this for a day+ now. here is my delema simple .ini text file. when a user makes a change (via html form) it makes the correct adjustments. problem is the newline issue 1. if i put a "\n" at the end (when using fputs) works great, except everytime they edit the file it keeps adding a new line (i.e. 10 edits there are now 10 blank lines!!!!) 2. if i leave off the "\n" it appends the next "fgets" to that lilne making a mess Code: [Select] ##-- Loop thruoght the ORIGINAL file while( ! feof($old)) { ##-- Get a line of text $aline = fgets($old); ##-- We only need to check for "=" if(strpos($aline,"=") > 0 ) { ##-- Write NEW data to tmp file fputs($tmp,$info[$i]." = ".$rslt[$i]."\n"); $i++; } ##-- No Match else { fputs($tmp,$aline."\n"); }//Checking for match }//while eof(old) what in the world is making this such a big deal. i dont remember having this issue in the past I tried opening with w+, and just w on the temp file a typical text line would be some fieldname = some value the scipt cycles through the file ignoring comments that are "#" ps the tmp file will overwrite the origianl once complete all i really want to know is WHY i cant get the newline to work, and what is the suggested fix EDIT: i just tried PHP_EOL and it still appends another newline |