PHP - Import File And Read The Contents
Hi,
I assigned a project where i have to import the mobile numbers from the file, but i have no idea how to proceed this. What kind of file to accept as input and how to read. Thanks Similar TutorialsI am looking for a way to upload a csv file to a website and have it populate a database. Does anyone know of a way to do this. The users of the site are novice website users and I am a novice php coder. Any help would be hugely appreciated. Thanks Hi All, sure this is simple but I'm still new to php/mySQL so errors are abundant! I have a simple form with one input: a browse button so the user can find a .csv file on their computer. User then clicks button, upon which I would like the file to be read and the contents put into an array, and the values to be added to the database. I do not need the file to be stored (uploaded). So far my code is not erroring, it just doesn't add the values to the db. I'm wondering if it's just that I HAVE to upload and save the file to the webserver else I can't read it? if(isset($_FILES['file_path']['tmp_name'])&& $_FILES['file_path']['tmp_name'] !=''){ $file_to_import = $_FILES['file_path']['tmp_name']; $import_data = file($file_to_import); print_r($import_data); if ($import_data !=''){ for($index = 1; $index < sizeof($import_data); $index++){ $order_data = explode(",",$import_data[$index]); tep_db_query("UPDATE orders SET act_shipping_cost = '" . $order_data[8]. "' WHERE orders_id = '". $order_data[0]."'"); echo "done it"; } }else{ echo 'error cant read file!'; } } else{ ?> <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> etc etc etc <form id="shipping_costs_upload" name="csv_file_reader" method="post" action="shipping_cost_upload.php"> <div class="main" id="info_text"><h2>Upload Actual Shipping Costs CSV</h2><p>To upload actual shipping cost data, browse to your csv and click the Upload Data button.<br /><br /></p> <div class="date" id="file"> <strong>CSV File: </strong><input type="file" name="file_path" id="file_url" /> </div> <div class="date"><input type="submit" value="Upload Data"> </div> </form> etc etc etc Apologies if I'm being a complete dunce! I am trying to import csv file to wordpress using database.the files are uploaded in database but its not coming in wordpress . The code is as below: <?php if(isset($_POST['submit'])) { $fname=$_FILES["file"]["name"]; $datetime=$_FILES["file"][""]; $chk_ext = explode(".",$fname); if(strtolower(($chk_ext[1]) == "csv")) { $filename = $_FILES['file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $fname=addslashes($data[0]); $datetime=addslashes($data[1]); $products=addslashes($data[2]); $preset=addslashes($data[3]); $format=addslashes($data[4]); $sql = "INSERT into ".$wpdb->prefix ."facebook(filename,datetime,products,preset,format) values('$fname','$datetime','$products','$preset','$format')"; mysql_query($sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> <form enctype="multipart/form-data" action="" method="post" name="uploadDetails"> <table cellpadding="4" cellspacing="0" border="1"> <tr> <td><label for="upload_a_file">Upload File:</label></td> <td><input type="file" name="file" id="upload_a_file" /></td> </tr> <tr> </tr> </table> <input type="hidden" name="fd_upload" value="1" /> <input type="submit" value="Submit" class="allbutton" name="submit" /> </form> Hope you will help me Hello, I am new to PHP and am trying to make a script that will ftp into the server via a cron of every hour or so and save the data to a mysql table. The first step is to draw variables out of information in the file via ftp. Its a ban list for a game server I run. How could I get php to single out the ban reason, admin, etc. the looks like this Code: [Select] "STEAM_0:0:42741441" { "name" "good mom" "unban" "0" "time" "1329161245" "admin" "(Console)" "reason" "no more trolling for you" } "STEAM_0:1:40563669" { "unban" "0" "admin" "Headcrap(STEAM_0:1:42287608)" "time" "1332855999" "reason" "" } "STEAM_0:1:17693550" { "name" "ʎɖɑɱ" "time" "1323055427" "modified_time" "1323221308" "unban" "0" "modified_admin" "Strategos(STEAM_0:0:26662109)" "admin" "Strategos(STEAM_0:0:26662109)" "reason" "And so died the trolling" } Example: Code: [Select] <?php $bannedid = "STEAM_0:0:42741441"; $bannedby "(console)"; // and so on ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Import a CSV File with PHP & MySQL</title> </head> <body> <form action="" method="post" enctype="multipart/form-data" name="csv" id="csv"> Choose your file: <br /> <input name="csv" type="file" id="csv" /> <input type="submit" name="Submit" value="Submit" /> </form> </body> Hello, this script originally works by reading a physical copy of 'bans.txt' located in the same directory. How could I get it to read the remote bans.txt located here and parse info from it like the on-site copy? the remote file: http://108.163.211.219/bans.txt Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Data Tables and Cascading Style Sheets Gallery</title> <style>/* Tema: Soft Table - A Simple table style with the use of the soft brown color Author: Newton de G?es Horta Site: -- Country Origin: Brazil */ table { font-size:0.9em; font-family: Arial, Helvetica, verdana sans-serif; background-color:#fff; border-collapse: collapse; width: 100%; } caption { font-size: 25px; color: #1ba6b2; font-weight: bold; text-align: left; background: url(http://www.nghorta.com/csstg/header_bg.jpg) no-repeat top left; padding: 10px; margin-bottom: 2px; } thead th { border-right: 1px solid #fff; color:#fff; text-align:center; padding:2px; text-transform:uppercase; height:25px; background-color: #a3c159; font-weight: normal; } tfoot { color:#1ba6b2; padding:2px; text-transform:uppercase; font-size:1.2em; font-weigth: bold; margin-top:6px; border-top: 6px solid #e9f7f6; } tbody tr { background-color:#fff; border-bottom: 1px solid #f0f0f0; } tbody td { color:#414141; padding:5px; text-align:left; } tbody th { text-align:left; padding:2px; } tbody td a, tbody th a { color:#6C8C37; text-decoration:none; font-weight:normal; display:block; background: transparent url(http://www.nghorta.com/csstg/links_yellow.gif) no-repeat 0% 50%; padding-left:15px; } tbody td a:hover, tbody th a:hover { color:#009193; text-decoration:none; } /* tr:nth-child(even) { background-color: grey; } */ </style></head> <body> <table summary="Submitted table designs"> <thead><tr> <th style="font-size:12px" scope="col"><center>Nickname</center></th> <th style="font-size:12px" scope="col"><center>Admin</center></th> <th style="font-size:12px" scope="col"><center>Banned</center></th> <th style="font-size:12px" scope="col"><center>Reason</center></th> <th style="font-size:12px" scope="col"><center>SteamID</center></th> <th style="font-size:12px" scope="col"><center>Length</center></th> <th style="font-size:12px" scope="col"><center>Status</center></th> </tr></thead> <tbody> <!-- <tr><th scope="row" id="r100"><a href="100.php">rows table template</a></th> <td><a href="http://www.adobati.it">Omar '0m4r' Adobati</a></td><td>Italy</td> <td>Simple, clean and a quite classic table template :)</td> <td><a href="http://www.adobati.it/labs/CSSTable/0m4r.table.css" title="Download the rows table template CSS file">Download</a></td> <td>test</td> <td>test2</td> </tr> --> <?php // Credits to justin as he was able to understand my messy PHP code and do this much better code for me. function buildBanList($arr) { $filename = "bans.txt"; $bans = array(); $tmp_array = array(); // Build Ban Array if (file_exists($filename)) { foreach( $arr as $line ) { if( substr(trim($line), 0, 7) == '"STEAM_' ) { $tmp_array["user_steamid"] = str_replace('"', '', trim($line)); } if( substr(trim($line), 0, 6) == '"time"' ) { $tmp = explode(' ', trim($line)); $tmp_array["user_bantime"] = str_replace('"', '', $tmp[1]); } if( substr(trim($line), 0, 15) == '"modified_time"' ) { $tmp = explode(' ', trim($line)); $tmp_array["user_modified"] = str_replace('"', '', $tmp[1]); } if( substr(trim($line), 0, 7) == '"unban"' ) { $tmp = explode(' ', trim($line)); $tmp_array["user_unban"] = str_replace('"', '', $tmp[1]); } if( substr(trim($line), 0, 7) == '"admin"' ) { $tmp = explode('" "', trim($line)); $tmp2 = explode('(', $tmp[1]); $tmp_array["admin_name"] = str_replace('"', '', $tmp2[0]); } if( substr(trim($line), 0, 6) == '"name"' ) { $tmp = explode('" "', trim($line)); $tmp_array["user_name"] = str_replace('"', '', $tmp[1]); } if( substr(trim($line), 0, 8) == '"reason"' ) { $tmp = explode('" "', trim($line)); $tmp_array["user_reason"] = str_replace('"', '', $tmp[1]); } // Save ban record to main array once detected end. if( substr(trim($line), 0, 1) == '}' ) { // If console ban then set required fields. if( $tmp_array["admin_name"] == "") $tmp_array["admin_name"] = "Console"; array_push($bans, $tmp_array); $tmp_array = array(); } } } //Sort Array by Ban Date $tmp = array(); foreach($bans as &$ma) $tmp[] = &$ma["user_bantime"]; array_multisort($tmp, SORT_DESC, $bans); return $bans; } //Begin Presentation $file = file("./bans.txt"); date_default_timezone_set("Europe/London"); $bans = buildBanList($file); foreach ($bans as $ban) { echo '<tr> '; // Output if ($ban["user_name"] != '') echo '<td style="text-align:center; font-size: 12px">'.$ban["user_name"].'</td><td style="text-align:center; font-size: 12px" class="admin">'; else echo '<td style="text-align:center; font-size: 12px"><span style="color:#FF0000">N/A</span></td><td style="text-align:center; font-size: 12px" class="admin">'; echo $ban["admin_name"].'</td><td style="text-align:center; font-size: 12px">'.date('H:i - d/m/y',$ban["user_bantime"]).'</td>'; /* Unban date. if ($ban["user_unban"] != "0") { echo date('H:i - d/m/y',$ban["user_unban"]); } else { echo "Never"; }*/ echo '<td style="text-align:left; font-size: 11px">'.$ban["user_reason"].'</td>'; // Status $today = strtotime("now"); echo '</td><td style="text-align:center; font-size: 12px">'.$ban["user_steamid"].' </td>'; // Ban Length $date1 = date('y-m-d H:i:s',$ban["user_bantime"]); $date2 = date('y-m-d H:i:s',$ban["user_unban"]); $to_time=strtotime($date1); $from_time=strtotime($date2); $ban_length = round(abs($to_time - $from_time) / 60,0); if ($ban["user_unban"] != "0") { // Days if ($ban_length >= 1440) { $ban_length = round(abs($to_time - $from_time) / 24 / 60 / 60,0); // Years couldn't be arsed to think of another way to do it. if ( $ban_length >= 365 ) { $ban_length = round(abs($to_time - $from_time) / 360 / 24 / 60 / 60,0); if ($bans_length > 1) echo "<td style=\"text-align:center; font-size: 12px\">".$ban_length." Years </td>"; else echo "<td style=\"text-align:center; font-size: 12px\">".$ban_length." Year </td>"; } else echo "<td style=\"text-align:center; font-size: 12px\">".$ban_length." Days </td>"; } // Hours else if ($bans_length >= 60) { $ban_length = round(abs($to_time - $from_time) / 60 / 60,0); if ($bans_length > 1) echo "<td style=\"text-align:center; font-size: 12px\">".$ban_length." Hours </td>"; else echo "<td style=\"text-align:center; font-size: 12px\">".$ban_length." Hour </td>"; } else echo "<td style=\"text-align:center; font-size: 12px\">".$ban_length." Minutes </td>"; } else { echo "<td style=\"text-align:center; font-size: 12px\">Permanent</td>"; } if ($ban["user_unban"] == "0") echo '<td style="text-align:center; font-size: 12px"><span style="color:#FF0000">Banned</span></td>'; else if ( $today > $ban["user_unban"] ) echo '<td style="text-align:center; font-size: 12px"><span style="color:#008000">Expired</span></td>'; else echo '<td style="text-align:center; font-size: 12px"><span style="color:#FF0000">Banned</span></td>'; echo '</tr>'; } ?></table> <center><p>Web-based ULX bans by Russy.</p></center> </div> </body> </html> I've tried experimenting w/ stuff like Code: [Select] $filename = "http://108.163.211.219/bans.txt"; $contents = file_get_contents($filename); but it doesn't seem to want to work. Hi! I hope somebody can help me what im do wrong. i have checked that the data from the file is in $source_file but nothing imports to the database Code: [Select] <?php include('config.php'); include('opendb.php'); if(isset($_POST['upload'])) { $source_file = @$_POST['userfile']; //$source_file = fopen('http://localhost/test/upload/test.csv', 'r'); $target_table = 'foretag'; function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) { if (($handle = fopen("$source_file", "r")) !== FALSE) { $columns = fgetcsv($handle, $max_line_length, ","); foreach ($columns as $column) { $column = str_replace(".","",$column); } $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES"; while (($data = fgetcsv($handle, $max_line_length, ";")) !== FALSE) { while (count($data)<count($columns)) array_push($data, NULL); $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");"; mysql_query($query); } fclose($handle); } } function quote_all_array($values) { foreach ($values as $key=>$value) if (is_array($value)) $values[$key] = quote_all_array($value); else $values[$key] = quote_all($value); return $values; } function quote_all($value) { if (is_null($value)) return "NULL"; $value = "'" . mysql_real_escape_string($value) . "'"; return $value; } } include('closedb.php'); echo "<br>done<br>"; ?> Hi.. I have code for importing .xml file to database. the problem is I cannot upload my file but no error display. And also I got a problem in importing data from .xml file to database but not all row will be save. here is my code: Code: [Select] <?php $data = array(); $con = mysql_connect("localhost", "root",""); if (!$con) { die(mysql_error()); } $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $sql = "select * from sales_order"; $result = mysql_query($sql); if (!$result) { die(mysql_error()); } function add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth) { global $data; $con = mysql_connect("localhost", "root",""); if (!$con){ die(mysql_error());} $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $ProductType= $ProductType; $WorkOrder = $WorkOrder; $POIssueDate = $POIssueDate; $SalesMonth = $SalesMonth; $sql = "INSERT INTO sales_order (ProductType,WorkOrder,POIssueDate,SalesMonth) VALUES ('$ProductType','$WorkOrder','$POIssueDate','$SalesMonth')" or die(mysql_error()); mysql_query($sql, $con); $data []= array('ProductType'=>$ProductType,'WorkOrder'=>$WorkOrder,'POIssueDate'=>$POIssueDate,'SalesMOnth'=>$SalesMonth); } if ( $_FILES['file']['tmp_name'] ['error']) //f (empty($_FILES['file']['tmp_name']['error'])) { //$dom = DOMDocument::load('SalesOrder.xml'); $dom = DOMDocument::load($_FILES['file']['tmp_name']); $dom = DOMDocument::__construct(); $rows = $dom->getElementsByTagName('Row'); global $last_row; $last_row = false; $first_row = true; foreach ($rows as $row) { if ( !$first_row ) { $ProductType = ""; $WorkOrder = ""; $POIssueDate = ""; $SalesMonth = ""; $index = 1; $cells = $row->getElementsByTagName( 'Cell' ); foreach( $cells as $cell ) { $ind = $cell->getAttribute( 'Index' ); if ( $ind != null ) $index = $ind; if ( $index == 1 ) $ProductType = $cell->nodeValue; if ( $index == 2 ) $WorkOrder = $cell->nodeValue; if ( $index == 3 ) $POIssueDate = $cell->nodeValue; if ( $index == 4 ) $SalesMonth = $cell->nodeValue; $index += 1; } if ($ProductType=='' AND $WorkOrder=='' AND $POIssueDate=='' AND $SalesMonth=='') { $last_row = true; } else { add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth); } } if ($last_row==true) { $first_row = true; } else { $first_row = false; } } } ?> <html> <body> <table> <tr> <th>Sales Order</th> </tr> <?php foreach( $data as $row ) { ?> <tr> <td><?php echo( $row['ProductType'] ); ?></td> <td><?php echo( $row['WorkOrder'] ); ?></td> <td><?php echo( $row['POIssueDate']) ;?> </td> <td><?php echo( $row['SalesMonth'] ); ?></td> </tr> <?php } ?> </table> </body> </html> and I will attach my sample data and the data with color yellow background is only row I want to save to my database. Thank you so much.. I am using apache web server on linux. I am using PHP for web designing. On web server, i want to show the configuration data by reading the ini file. I am creating this ini file from one php code itself. If this php code i run through linux terminal, the file is created with file and group owner as root.(i am having sudo rights on machine) Then if i try to read the ini file from my apache web server, it gives warning as failed to open stream: permission denied. I have tried changing the owner, and permissions to 777 of the file. Still it is not readable.
On the other hand, if i run the php code of ini file creation through web server, ini file is created with file and group owner as apche. and web server is able to read/ write the file.
But i want to create that file from root or some other user and later read/written by apache.
How to give this access permission?
I think this is the right section to post this is in..... Anyway.....I'm building a web site that requires i have functionality to upload a tab delimited file (or some file format that is easiest) via php and insert the data into MYSQL. I've searched for many third party scripts but none seem to work. So I've decided to move to the community to see if someone can give me insight on how i might accomplish this script. I have some third party scripts but I'm not sure if they'd be of any use. Thank you kindly This script is supposed to run in the command line. Like the title says, I need to: Import some columns (input the names with an argument) from a .CSV file Split the column into blocks of 500 lines Translate this pieces Put them back into the original file I already have some code but it is unfinished and not working: <?php //name of the .CSV file $filename = $argv[1]; //name of the column to be translated $header_name = $argv[2]; //open file $file_handle = fopen($filename, "r"); $i=0; $j=0; $counter = 0; $translated = ''; $string = ''; while (!feof($file_handle) ) { $counter++; $line_of_text = fgetcsv($file_handle, 1024); //find the column id that contains the header name. // headers are always on the the first line if ( $counter == 1 ){ while ($line_of_text[$i] != $header_name) $i++; $header_id = $i; } //create the blocks $string .= $line_of_text[$i]; if ($counter % 500 == 0) { $gt = new GoogleTranslateWrapper(); $translated .= $gt->translate($string, "en"); } } //Write the translate column in the same .CSV file fclose($file_handle); ?> Any help in rewriting this to work? I need some help getting started in writing the php code that would import a text file of name/value pairs and then create an html table with those values. The datafile looks something like this: [number]-[attribute]=[value]; 1-Host=server1.abc.dev.jkl;2-Date=Wed Aug 12 2010;3-Set=abc.123.cde;4-Time=01:00:03;5-Length=00:36:09;6-Size=41.54 GB;7-Status=Succeeded; 1-Host=server2.abc.dev.qrs;2-Date=Wed Aug 12 2010;3-Set=gls202.kul_lvm;5-Length=06:20:33;7-Status=Succeeded; 1-Host=server9.mra.dev.xyz;2-Date=Wed Aug 11 2010;3-Set=gls101.aie_lvm;4-Time=01:00:02; Let's say I have an html table: Code: [Select] <table id="stats"> tr> <th>Host</th> <th>Date</th> <th>Set</th> <th>Time</th> <th>Length</th> <th>Size</th> <th>Status</th> </tr> <tr> <td>server1.abc.dev.jkl</td> <td>Wed Aug 12 2010</td> <td>abc.123.cde</td> <td>01:00:03</td> <td>00:36:09</td> <td>41.54 GB</td> <td>Succeeded</td> </tr> </table> I've looked around all day at various samples. I've seen the fgetcsv function. I'm not sure what would be the best approach to load this into data into a table. Using a regex, then load into array or hash and then print this out? I'm assuming i would have to create print statements to produce the html tags. Also, with the sample records I provided. There will be instances where not all the attributes (1-7) have values. So, i'm envisioning empty cells for that record which is fine. I can also change the way the datafile is generated and remove the [number], so its just [attribute]=[value] if that makes it easier. Is there a good mapping technique for this? Thank you for your help. 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 Hello friends, if i have the following $path = "http://*site*.com"; why can't i write the following $ORGtext= file_get_contents('$path'); it works only if i write $ORGtext= file_get_contents('http://*site*.com'); but i want to put $path instead of the url at file_get_contents is it possible and if yes then how ? thank you eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. Hello, I have a simply query that will if a simple two different things: Code: [Select] $cssyn = mysql_query("SELECT `12` FROM `12345` WHERE `abc` = '$_SESSION[number]'"); $cssy = mysql_fetch_row($cssyn); if($cssy[0] == "YES") { echo "Yes"; } else { echo "No"; } The YES or NO result is stipulated earlier on so thats not the problem. But basically before I added the if statement simply would have echoed a table with all the rows etc from another query. However I would like to give the user a choice between echoeing the results into one table or a neater two. I have separated the code for the table and the queries into two separate files but say if I use: file_get_contents then it just prints the HTML and doesnt actually populate it will the queried parts. Nor if I use something like include() then it wont echo anything, which it wouldnt unless called so what I am asking is: Is there a way to get EVERYTHING from the file if the answer is YES or the other file if NO. I'm trying to extract the contents of a zip file to a folder. I found the ZipArchive class and followed the examples to get it to work for the most part. But I want to extract the files in the folder inside the zip file but leave the folder out. So it should extract just the files to my given destination. I found this on php.net. Code: [Select] If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder). <?php $path = 'zipfile.zip' $zip = new ZipArchive; if ($zip->open($path) === true) { for($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); $fileinfo = pathinfo($filename); copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']); } $zip->close(); } ?> For some reason that 'copy' line is not working for me. Obviosly I've changed the variables in the line to the correct variables. Can someone help me out. Thanks Mike Hello, I am a PHP newbie, and have been mostly playing around with PHP/MySQL in a CMS ares (i.e. building my own CMS). Now I am trying to expand my knowledge outside of the basic php commands, and a particular subject caught my attention. Getting page source code, parsing out bits from it, and displaying it. This is more of my personal goal to get it working, to learn more about some of PHP's abilities, and especially search parameter flag thingies D: http://nexrem.com/scripts/get_source/ That is my webpage i made real quick, as you can see it shows basic stuff. Code for it is: Code: [Select] <html> <head> <title>Content Site</title> </head> <body> <p>This is intro text</p> <a href="http://google.com" title="Search Engine">Google Link</a><br /> <a href="http://yahoo.com" title="">Yahoo Page</a></br > <a href="http://http://www.phpfreaks.com" title="Awesome Site">PHP Freaks Help</a><br /> Bottom of file </body> </html> Now, I have a php file called get_link.php >> http://nexrem.com/scripts/get_source/get_links.php Code: [Select] <?php $url = 'http://nexrem.com/scripts/get_source/'; $needle = 'google'; $contents = file_get_contents($url); if(strpos($contents, $needle)!== false) { echo 'found'; } else { echo 'not found'; } // The \\2 is an example of backreferencing. This tells pcre that // it must match the second set of parentheses in the regular expression // itself, which would be the ([\w]+) in this case. The extra backslash is // required because the string is in double quotes. $html = $contents; echo $contents; preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); foreach ($matches as $val) { echo "matched: " . $val[0] . "\n"; echo "part 1: " . $val[1] . "\n"; echo "part 2: " . $val[2] . "\n"; echo "part 3: " . $val[3] . "\n"; echo "part 4: " . $val[4] . "\n\n"; } ?> From what I understand, file_get_contents gets what the user sees? Or it gets the source code, and I just can't output it as such, cause my browser renders it? Question 1: Is it possible to get the html code of the page, rather than what the html renders it to be? How? Question 2: I can just Right click > view source and paste that result into a text file. I think I know how to search for a specific string, but how would I do it recursively, along the lines of: Search for text between <a href=" and " so I get the raw link Then add the results to an array. And then use foreach to output all the links from the array? Any help, hints are appreciated! Thank You! P.S. I quite frankly, got no idea what "/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/ is... Can someone refer me to a page where I can learn about those expressions? i am trying to do a "file get contents" from the following website http://www.bet365.com/home/ It is necessary to input your account username and password here, and then I want to get the contents of this page http://www.bet365.com/extra/en/results-and-archive/results/?Fromdate=13%2f09%2f2014+00%3a00&SearchPath=result&FixtureId=46827110&Period=99&ChallengeId=26278650&CompetitionId=999999&SportId=1&SportDesc=Soccer&Todate=14%2f09%2f2014+00%3a00&LanguageId=1&Zoneid=1 I have tried a couple of scripts but just can't seem to get it to work. I have tried $context = stream_context_create(array( 'http' => array( 'header' => "Authorization: Basic " . base64_encode("$username:$password") ) )); $data = file_get_contents($url, false, $context); echo $data; with the username and password and url entered as variables. but get the message Warning: file_get_contents(http://www.bet365.com/extra/en/results-and-archive/results/?Fromdate=13%2f09%2f2014+00%3a00&SearchPath=result&FixtureId=46827110&Period=99&ChallengeId=26278650&CompetitionId=999999&SportId=1&SportDesc=Soccer&Todate=14%2f09%2f2014+00%3a00&LanguageId=1&Zoneid=1) [function.file-get-contents]: failed to open stream: HTTP request failed! in "myscript's address" on line 13 Maybe i don't need to visit the homepage first to log in? Any ideas please? Thank youapologies for the message being in code quotes, I wrote it in Word but then couldn't paste it, even using the special Word paste button. Hope the message comes out ok. Thank you. I set up a Twilio number so a client could have a SMS keyword response setup... but I don't know how to get the contents of a file to be returned as the response. I am using the php functions.. I setup a system so that my client could change the responses to different keywords. Basicly it uses a webform to change the contents of a file which gets returned as a response. What I need to know is how to read in the contents of the file into this function: BTW... this works fine and will return "READ_FILE_CONTENTS_INTO_HERE" function app(){ $response = new Services_Twilio_Twiml(); $response->sms("READ_FILE_CONTENTS_INTO_HERE"); echo $response; } I tried this but it stopped the script dead: function app(){ $response = new Services_Twilio_Twiml(); $response->sms("<?php include 'file.txt'; ?>"); echo $response; } Any ideas? Thanks BTW... below is the entire php script: <?php /* Include twilio-php, the official Twilio PHP Helper Library, * which can be found at * http://www.twilio.com/docs/libraries */ include('Services/Twilio.php'); /* Controller: Match the keyword with the customized SMS reply. */ function index(){ $response = new Services_Twilio_Twiml(); $response->sms("Thank You For Contacting SweetLeafAZ.com - Reply with one of the following keywords: APP = Make Appt, CS = Current Strains, DP = Delivery Prices, SP = Current Specials."); echo $response; } function app(){ $response = new Services_Twilio_Twiml(); $response->sms("http://www.vcita.com...01f2c7d/home"); echo $response; } function cs(){ $response = new Services_Twilio_Twiml(); $response->sms("http://mobile.dudamo...sweetleafaz2"); echo $response; } function dp(){ $response = new Services_Twilio_Twiml(); $response->sms("As of Sept 26 2014, Our Delivery Rates are $2 per mile during the hours of 9am to 6pm. No deliveries will be made after 6pm."); echo $response; } function sp(){ $response = new Services_Twilio_Twiml(); $response->sms("We are currently offering FREE delivery within 10 miles for orders over $100."); echo $response; } /* Read the contents of the 'Body' field of the Request. */ $body = $_REQUEST['Body']; /* Remove formatting from $body until it is just lowercase characters without punctuation or spaces. */ $result = preg_replace("/[^A-Za-z0-9]/u", " ", $body); $result = trim($result); $result = strtolower($result); /* Router: Match the ‘Body’ field with index of keywords */ switch ($result) { case 'app’': app(); break; case 'cs': cs(); break; case 'dp': dp(); break; case 'sp': sp(); break; /* Optional: Add new routing logic above this line. */ default: index(); } |