PHP - Basic Php: Getting File Contents, Parsing It
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? Similar TutorialsHi All, I'm having a major mind blank, and can't find anything in the previous posts resolving what I'm after. I'm setting $searchtext = $_POST['searchtext']; I want to check $seachtext is not null. I've seen isset($searchtext) but it doesn't solve my problem. Basiclaly; I want an if statement to say if(isset($searchtext)) {......} Thoughts? 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 I know how to parse and print out contents of an XML file with SimpleXML but when I do it with this one I just get an empty string. XML file sample: Code: [Select] <?xml version="1.0"?> <?mso-application progid="Excel.Sheet"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <Title>Periodens vara - maj</Title> <Company>Company1</Company> <Version>1.00</Version> </DocumentProperties> <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"> <AllowPNG/> </OfficeDocumentSettings> <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> <WindowHeight>10005</WindowHeight> <WindowWidth>10005</WindowWidth> <WindowTopX>120</WindowTopX> <WindowTopY>135</WindowTopY> <ProtectStructure>False</ProtectStructure> <ProtectWindows>False</ProtectWindows> </ExcelWorkbook> <Styles> <Style ss:ID="Default" ss:Name="Normal"> <Alignment ss:Vertical="Bottom"/> <Font ss:FontName="Calibri" ss:Size="11" ss:Color="#000000"/> </Style> .... I get no error so the structure is correct. But doing print_r() returns an empty array. So does children(). How do I start, help me out It will be a txt file and I need to parse it and insert it into a mysql, I know there are many parser examples out there, but half I don't understand...... this is how the file is... I'll also attach it... Code: [Select] [5/3/2011 12:37:14]: SuspectsKill: TeK_SiC Pwn^Guandi 9mm SMG I need to place the killer and the person who got killed, I don't really need the weapon if there not in the db I need to enter it..... and if they are I need it to add a kill on there name... this is just some of the log.. thanks for the help! Hi all, I have a text file with few IP ranges in the following format: 1.52.0.0 - 1.55.255.255 What I hope I can do is to loop through the file content and retrieve the start IP / end IP (each in a variable) so that I can work on each of them. So for example for the line above I wish to get (1.52.0.0) in a var and (1.55.255.255) in another var while looping the file content So I was wondering if I can get any help on how to do this using PHP? Please excuse me if this seem to be very easy question but I am quite new to php, so any code help will be highly appreciate Thanks for your time Mark 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. eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. Here's what I need to do: I have a page that reads file and simply echos it. $mystring = file_get_contents($file); echo "$mystring"; There is one piece of info I need to parse out and then use as part of my page title. The phrase I need to parse is an HTML comment field and looks like this: <!--PageTitle=<some text here> --> I'm sure this is simple but I'm clueless as you can tell. How can I do this? DryAquaman Hi, As I am new to PHP and JSON my Interest in the field pushes me to know further. I have successfully parsed a JSON file: { "birthdays": [ "319507200" :"Kyle", "1390435200" :"Noah", "307843200" :"Carla" ] } Using this PHP file: <?php $jsondata = file_get_contents("birthdays.json"); $json = json_decode($jsondata,true); echo $json["birthdays"][0]['1390435200']; ?> Now I would like to know how to display when Noah’s birthday is, in the form yyyy/MM/dd. Can an expert tell me how this would be done? Thank you :-) having a problem importing a file having multiple hierarchy levels!! its a csv file the contents look something like this! just need a jump start! thanks the file looks likes this row 1 row2 row3 name1 subj1 abcd efgh subje2 test1 test2 the file has to first import name1 then subj1 then abcd,then efgh then move back to subj2 and so on! Thanks hi php freaks, Is there a way to parse an include file through the php engine and then place the contents into a variable? Code: [Select] $x = include ($myfile); 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(); } is there a way to print the file as it appears. I want to print the HTML and PHP within a file rather than just the output. Example: File contains: <?php echo "Hello World"; ?> i would like to echo: <?php echo "Hello World"; ?> instead of just hello world which is what i get with file_get_contents() 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'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 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 Hi, I have a file which contains settings for a user. Similar to wordpress except simpler like setting a default email for error messages or something. The idea is that it's used as an installation script for web-ware where someone fills in a form with their database details, my script will hard-code them into the settings file and then delete itself. I'll admit I did get the idea from wordpress. Only the way it's coded currently requires a certain combination of characters at the end and seems really messy. The script looks like this (and does work): $endpos = strpos ( $contents, '"; //replace with name//', $startpos); The settings file looks like this: $hard_name = "Smith"; //replace with name// As you can see I use the comment in the settings file, which follows what I'm actually changing, to find the end of the variable. I am sure there must be a better way of doing things but don't know what. It just seems really inefficient because if the comment is removed the script breaks. Any info and tips would be much appreciated. IceKat |