PHP - How To Save Results From Foreach Into Txt File
I would like to write all files from specific folder into .txt file. The output working just fine, but I'm getting only one file saved into my txt file. Any idea? Thanks! $fileList = glob('C:\users\John\Documents\*pdf'); foreach($fileList as $filename){ if(is_file($filename)){ echo $filename, '<br>'; $save_files = fopen("list.txt", "w"); fwrite($save_files,$filename); fclose($save_files); } }
Similar TutorialsHi, I have the admin module, there i would like to save the searched results, how to save my searched rows , how to do it, Help appreciated, thank you How can I limit my foreach to displaying three results? In addition, how can I make it say... if results == 1 do this if results == 2 do this and if results == 3 do this Code: [Select] foreach($otherfans as $other) { $displayName = ucwords($other['firstname'].' '.$other['lastname']); ?> <a href="../u/<?php echo $other['username']; ?>"><?php echo $displayName; ?></a> <?php } I am using a foreach loop to get the results of an array. My problem is that I need the results combined into one string. How can I accomplish this? Hello everyone !
I am currently developing a module for my site that will allow me to classify each solution to help a disability by type. Type : Visual disability Solution : Add screen readers For this, I have a database in which these types and solutions are found. In this database, the solutions of one type or another are not in a defined order. They can be put randomly, when a user adds one. I need to display, in a table, these Types first (as a title), then the solutions corresponding to this type. I manage to generate a display thanks to a foreach loop, but my solutions are all mixed up and therefore not clearly sorted.
Visual disability Audio-described cut-scenes Highlighted path to follow Sensitivity settings for all the controls Screen readers on menus Slow down the game speed But I would need it to look like this: Visual disability Audio-described cut-scenes Highlighted path to follow Screen readers on menus Slow down the game speed Physical disability Sensitivity settings for all the controls In my example above, only the solution "Sensitivity settings for all the controls" is part of the "Physical disability" type. The rest is part of the "Visual disability" type. Here is the code I currently use to retrieve my information from my database and display it. It's a Wordpress.
/*====== Accessibility Options ======*/ function cloux_accessibility_options() { if ( function_exists( 'rwmb_meta' ) ) { $output = ""; $accessibility_options = rwmb_meta( 'accessibility-options' ); $accessibility_options_status = rwmb_meta( 'accessibility-options-status' ); if( $accessibility_options_status == "1" ) { if( !empty( $accessibility_options ) ) { $output .= '<div class="accessibility-options widget-box">'; $output .= cloux_title( $title = esc_html__( 'Accessibility Options', 'cloux' ), $style = "style-4", $align = "left", $colored_title = '' ); $output .= '<ul>'; $output .= '<li class="title visual_disability">' . esc_html__( 'Visual disability', 'cloux' ) . '</li>'; $output .= '</ul>'; foreach ( $accessibility_options as $accessibility_options ) { if( !empty( $accessibility_options ) ) { $accessibility_name = isset( $accessibility_options['accessibility-options-name'] ) ? $accessibility_options['accessibility-options-name'] : ''; $accessibility_type = isset( $accessibility_options['accessibility-type-name'] ) ? $accessibility_options['accessibility-type-name'] : ''; $accessibility_type = get_term( $accessibility_type, 'accessibility' ); $accessibility_type_name = $accessibility_type->name; $availability = isset( $accessibility_options['availability'] ) ? $accessibility_options['availability'] : ''; if ( $accessibility_type_name == "Visual disability" ){ if( !empty( $accessibility_name ) or !empty( $availability )) { $output .= '<ul>'; $output .= '<li class="item accessibility_name">'; if( !empty( $accessibility_name ) ) { $accessibility_name = get_term( $accessibility_name, 'accessibility' ); if( ( !empty( $accessibility_name ) ) ) { $output .= '<a href="' . get_term_link( $accessibility_name ) . '">' . esc_attr( $accessibility_name->name ) . '</a>'; } } $output .= '</li>'; $output .= '<li class="item visual_disability status">'; if( $availability == "1" ) { $output .= '<i class="fas fa-check" aria-hidden="true"></i>'; } else { $output .= '<i class="fas fa-times" aria-hidden="true"></i>'; } $output .= '</li>'; } } if ( $accessibility_type_name == "Motor/Physical disability" ){ if( !empty( $accessibility_name ) or !empty( $availability )) { $output .= '<ul>'; $output .= '<li class="item accessibility_name">'; if( !empty( $accessibility_name ) ) { $accessibility_name = get_term( $accessibility_name, 'accessibility' ); if( ( !empty( $accessibility_name ) ) ) { $output .= '<a href="' . get_term_link( $accessibility_name ) . '">' . esc_attr( $accessibility_name->name ) . '</a>'; } } $output .= '</li>'; $output .= '<li class="item visual_disability status">'; if( $availability == "1" ) { $output .= '<i class="fas fa-check" aria-hidden="true"></i>'; } else { $output .= '<i class="fas fa-times" aria-hidden="true"></i>'; } $output .= '</li>'; } } $output .= '</ul>'; } } $output .= '</div>'; } } return $output; } } Thank you in advance for all the help you can give me! Edited January 13 by Sagaroth HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hello, i have the code below and i need to have all results in a variable as a string, inside the loop they are displayed how i want but outside will echo the last result. Thank You. Code: [Select] foreach($_POST as $key=>$value){ if (is_numeric($value)) { $valoare = "$value,"; } } echo $valoare; I have a search form that has a drop down Code: [Select] <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> I'm trying to limit the results in a foreach loop within what was selected. Meaning, if someone selects 10, results within 10 miles will show The foreach is Code: [Select] foreach ($stores as $k=>$v) { $output = "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['MktName']."</b><br>(approx ".$v." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'>".$storeinfo[$k]['LocAddSt']."<br>"; $output .= $storeinfo[$k]['LocAddCity'].", ".$storeinfo[$k]['LocAddState']." ".$storeinfo[$k]['zipcode']."</p>"; print_r($output); } $v being the distance. So I need to show only the results of $v that are less than $r. How would I go about doing this? Right now, $v displays numbers like 5.04, 173.9 and so forth. Can anybody help me out? Thanks in advance. I want to save files to a directory. I am using a input type="text" to let user paste directory, then they choose the file from an upload form, then press submit. So here is my script: ============== <form method="post" action="" enctype=...> <input type="text" name="textboxDir" /> <input type="file" name="uploadedFile"/> </form> So how do I now save the uploaded file via $_POST['uploadedFile'] to the text box directory: $_POST["textBoxDir"]? Any help much appreciated! Hi Everyone, i need some help how can i save this jsonfile to the webserver? my code // Load initial values from JSON 'file' jsonfile = '[{"lane 1":"1","lane 2":"1","lane 3":"5","lane 4":"2"}]'; var initialstate = JSON.parse(jsonfile); setLaneState("lane1",initialstate[0]['lane 1']) setLaneState("lane2",initialstate[0]['lane 2']) setLaneState("lane3",initialstate[0]['lane 3']) setLaneState("lane4",initialstate[0]['lane 4'])
Hi, I am trying to save some content with form which has php code in it. i.e $submittedphpcode <?php echo 'test'; ?> my code to save that $submittedphpcode $file = "file.php"; $ourFileHandle = fopen($filefile, 'w+') or die("can't open file"); fwrite($ourFileHandle, "$submittedphpcode"); fclose($ourFileHandle); and i am getting this file created with slashes <?php\r\n\r\necho \'test\';\r\n\r\n?> i tried with stripslashes but it just remove \ not r n , i need to keep spaces etc. any help on how to save it as php file properly? Thanks I have this code header("Content-type: text/xml"); $database = "rprice"; $linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host."); mysql_select_db($database, $linkID) or die("Could not find database."); $query = "SELECT * FROM plist ORDER BY date DESC"; $resultID = mysql_query($query, $linkID) or die("Data not found."); $xml_output = "<?xml version=\"1.0\"?>\n"; $xml_output .= "<graph>\n"; for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ $row = mysql_fetch_assoc($resultID); $xml_output .= "\t<set date =\"" . $row['date'] . "\" value =\"" . $row['sprice'] . "\">\n"; $xml_output .= "\t</set>\n"; } $xml_output .= "</graph>"; echo $xml_output; I want to save this xml file into the folder name Data what is the code of that please help Hello all. I have a script that exports data from mysql to a csv file. Everything works great. However, I do not know how to save the csv file to the server. Does anyone have any ideas how I would do that? The script is below. Thanks for all help! Code: [Select] <?php $host = 'localhost'; $user = ''; $pass = ''; $db = ''; $table = ''; $file = 'export'; function escape_csv_value($value) { $value = str_replace('"', '""', $value); // First off escape all " and make them "" if(preg_match('/,/', $value) or preg_match("/n/", $value) or preg_match('/"/', $value)) { // Check if I have any commas or new lines return '"'.$value.'"'; // If I have new lines or commas escape them } else { return $value; // If no new lines or commas just return the value } } $link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error()); mysql_select_db($db) or die("Can not connect."); $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].", "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= escape_csv_value($rowr[$j]).','; //$csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); //header( "Content-Type: application/save-as" ); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: attachment; filename=".$filename.".csv"); //header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?> Hello, I'm editing an XML file using PHP, the XML file contains a playlist of songs for a flash mp3 player. Now I'm able to edit the XML file, but I'm not able to save it . Here's my code: $random_speed = mt_rand(1,15); // Discspeed $song_title = /*mysql_real_escape_string($_GET['song_title'])*/ "My First XML Edit"; $song_artist = /*mysql_real_escape_string($_GET['song_artits'])*/ "A great author"; $song_filename = /*basename(mysql_real_escape_string($_GET['song_filename']))*/ "myfirstxmledit.mp3"; /* Open image directory and get a random image name */ $dir = "./img"; /* Scan the directory and put everything in an array */ $files = scandir($dir); /* Count the elements in the array */ $count_array = count($files); /* Pick a random index from the array */ $rand_array = array_rand( $files, 1 ); /* Pick the value of the random index */ $random_image = $files[$rand_array]; /* Loop through array and if element is not equal to "." or ".." then set the random_image variable */ if( ($random_image == "." ) || ($random_image == ".." ) ){ while( ($random_image == "." ) || ($random_image == ".." ) ){ $random_image = $files[$rand_array]; } }elseif( ($random_image != "." ) || ($random_image != ".." ) ){ echo $random_image; } /* Open the music.xml file */ $xml = new DOMDocument('1.0', 'utf-8'); $xml->formatOutput = true; $xml->preserveWhiteSpace = false; $xml->load('music.xml'); /* Begin settin new element to music.xml file */ $newItem = $xml->createElement('song'); $newItem->appendChild($xml->createElement('title', "'$song_title'")); $newItem->appendChild($xml->createElement('artist', "'$song_artist'")); $newItem->appendChild($xml->createElement('url', "songs/'$song_filename'")); $newItem->appendChild($xml->createElement('image', "img/'$random_image'")); $newItem->appendChild($xml->createElement('discspeed', $random_speed)); /* Add the new elements to the xml tag 'song' */ $xml->getElementsByTagName('song')->item(0)->appendChild($newItem); /* Save the xml file */ $xml->save(); I've tried to enter the filename in the last $xml->save() function, didn't work, added the location + filename, didn't work ... Anyone knows what or how do I save the file? Thanks! Hello, I want to do, when someone click on button/link will open this: but not Save As, but Open. I know how to make simple form: <html> <body> <form action="edit.php" method="post" enctype="multipart/form-data"> <label for="file">File:</label> <input type="file" name="file" id="file" /> <br><br> <input type="submit" name="submit" value="Open"/> </form> </body> </html> But here You must click Browse, but I want to do like in photo: if You click on button, then at once will open form like photo. Many thanks, Tadas P.S. Sorry for my really bad English. Hi, Very new to PHP and am enjoying learning the ins and outs etc, but while creating my mam a website, ive ran into a problem while uploading, resizing and saving the file to my web host. Initially i used imagecreatefromjpeg, but this was taking too much memory up, so opted to use imagemagick. All of the features work apart from the file getting saved to the uploads directory on my web space. They always get saved to the root. If someone could help i would be very grateful. The code ive got currently is: <?php // If the form has been submitted do this if(isset($_POST['submit'])) { // Temporary upload image name $original_image = $_FILES['photo']['tmp_name']; // Get the image dimensions $size=GetImageSize( $original_image ); // Name to save the image as - in this case the same as the original $new_image = $_FILES['photo']['name']; // Maximum image width $max_width = "600"; // Maximum image height $max_height = "300"; // Resize the image and save exec("convert -size {$size[0]}x{$size[1]} $original_image -thumbnail $max_widthx$max_height $new_image"); echo "File uploaded<br>"; echo "<img src=\"".$new_image."\">"; } ?> Hopefully someone could help Many thanks, Matk. How can i handle what the user clicked in the Save File Dialog Box? if(user clicked "save") { i will send them an email; } else if (user clicked "cancel") { i will not send them an email; } is this possible? Please help me out guys. Thankyou Hi Chaps, I'm working on a PHP script to mysqldump database to file. Using this as a base: http://www.edmondscommerce.co.uk/mysql/php-mysql-dump-script/, I've managed to strip it down to this: Code: [Select] set_time_limit(0); $mysql_host='localhost'; $mysql_database='database'; $mysql_username='username'; $mysql_password='pasword'; _mysql_test($mysql_host,$mysql_database, $mysql_username, $mysql_password); $print_form = 0; header('Content-type: text/plain'); header('Content-Disposition: attachment; filename="'.$mysql_database."_".date('Y-m-d').'.sql"'); $filename = $mysql_database."_".date('Y-m-d').'.sql'; _mysqldump($mysql_database); function _mysqldump($mysql_database) { $sql="show tables;"; $result= mysql_query($sql); if( $result) { while( $row= mysql_fetch_row($result)) { _mysqldump_table_structure($row[0]); _mysqldump_table_data($row[0]); } } else { echo "/* no tables in $mysql_database */\n"; } mysql_free_result($result); } function _mysqldump_table_structure($table) { echo "/* Table structure for table `$table` */\n"; echo "DROP TABLE IF EXISTS `$table`;\n\n"; $sql="show create table `$table`; "; $result=mysql_query($sql); if( $result) { if($row= mysql_fetch_assoc($result)) { echo $row['Create Table'].";\n\n"; } } mysql_free_result($result); } function _mysqldump_table_data($table) { $sql="select * from `$table`;"; $result=mysql_query($sql); if( $result) { $num_rows= mysql_num_rows($result); $num_fields= mysql_num_fields($result); if( $num_rows> 0) { echo "/* dumping data for table `$table` */\n"; $field_type=array(); $i=0; while( $i <$num_fields) { $meta= mysql_fetch_field($result, $i); array_push($field_type, $meta->type); $i++; } echo "insert into `$table` values\n"; $index=0; while( $row= mysql_fetch_row($result)) { echo "("; for( $i=0; $i <$num_fields; $i++) { if( is_null( $row[$i])) echo "null"; else { switch( $field_type[$i]) { case 'int': echo $row[$i]; break; case 'string': case 'blob' : default: echo "'".mysql_real_escape_string($row[$i])."'"; } } if( $i <$num_fields-1) echo ","; } echo ")"; if( $index <$num_rows-1) echo ","; else echo ";"; echo "\n"; $index++; } } } mysql_free_result($result); echo "\n"; } function _mysql_test($mysql_host,$mysql_database, $mysql_username, $mysql_password) { global $output_messages; $link = mysql_connect($mysql_host, $mysql_username, $mysql_password); if (!$link) { array_push($output_messages, 'Could not connect: ' . mysql_error()); } else { array_push ($output_messages,"Connected with MySQL server:$mysql_username@$mysql_host successfully"); $db_selected = mysql_select_db($mysql_database, $link); if (!$db_selected) { array_push ($output_messages,'Can\'t use $mysql_database : ' . mysql_error()); } else array_push ($output_messages,"Connected with MySQL database:$mysql_database successfully"); } } The problem is, I want the file to save to a specific network location, rather than the output being sent to headers. I've tried to play around with: Code: [Select] ob_start();.... $page = ob_get_contents(); ob_end_flush(); $fp = fopen("output.html","w"); fwrite($fp,$page); fclose($fp); But this outputs to the browser, then saves the file...I would like to load the page, and have the script create and save the file where I want it (without the output in the browser, or prompt to save/download file). Note: I need something like this as I'm running PHP/MySQL on IIS, so can use shell/system/etc. Any help will be hi-5-tastic! I want that my script remotely download a file on the server from another server and save it remotly on the server.
For example my script is located on http://mydomain.com/...load_script.php
The file I want to download is on http://otherdomain.com/file.zip
Then I want to save it to http://mydomain.com/file.zip ----------- to the local server folder
I found a way how to parse HTML code remotly, but haven't found how to download files, please help me to find the right function.
Hello, i need some help/info about searching words in files (txt or xml) and saving them to db or another file.
For example ive got an xml file like below:
<families>
<family>
<name>brown</name>
<city>denver</city>
<members>12</members>
</family>
<family>
<name>jackson</name>
<city>new york</city>
<members>6</members>
</family>
</families>
i want to search for: <family> then save the lines till it comes to the word </family> and then goes to the next group. did some reading about array, preg_match, strpos functions but dont know where to start. what is the best way to do this?
can you guys give me some advise... or links to good tutorials?
thanks in advance!
I have a textarea and a button, I would like by click a button, the text within the textarea will save as a .txt file and downloadable by user, how to do it with php?? Thanks!! |