PHP - Help With Simplexml_load_file When File Doesn't Exist
I have a script that uses simplexml_load_file to download weather xml files. It works great except when the file doesn't exist. The server returns an HTML page when the xml file isn't available but the title is something.xml. How can I check to be sure it is an xml file and handle the error when it isn't. I have tried file_exists and access the return code (it's always 200). Can I access the doctype and determine if it HTML or XML?
Similar TutorialsI'm trying to do a simple image upload. It works fine on my local server but i'm moving all my files to my production server and some files i attempt to upload, via an html form, don't register. The $_FILES variable doesn't exist sometimes. I think its because of the file size but i'm not sure. The form has two inputs: "title" and "userfile". I can put something in the title and attempt to upload a small excel file and both $_POST and $_FILES exist but if i do a larger image file both $_POST and $_FILES don't even get set. I did an "echo ini_get('post_max_size');" and i get "8M". The image i'm attempting to upload is only 0.34M so i should be good there. I've replaced the actual upload script with this, which is how i found out the variables only get set sometimes Any suggestions would be much appreciated. Code: [Select] <?php echo "Upload: " . $_FILES["userfile"]["name"] . "<br />"; echo "Type: " . $_FILES["userfile"]["type"] . "<br />"; echo "Size: " . ($_FILES["userfile"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["userfile"]["tmp_name"]; echo "<hr><pre>"; print_r($_POST); echo "</pre><hr>"; echo "<pre>"; print_r($_FILES); echo "</pre>"; And how can I make it so if it does already exist, it doesn't over-write information already in it? Thanks *delurk! It had to happen sooner or later!* OK, I am totally and utterly stumped. I have this script: $this->clear_cache ($this->cache_dir, $this->cache_time); if ($this->cache_time > 0) { $current_page = $_SERVER ['REQUEST_URI']; $current_page_encoded = base64_encode($current_page); $current_page_path = $this->cache_dir . $current_page_encoded; if (file_exists($current_page_path)) { // see if there is still a file with the name of the current request URI after cache cleared $content = file_get_contents ($current_page_path); return $content; } } Basically, it is for checking if there is a cached version of the page before running the rest of the script, using the REQUEST_URI as the identifier. So it calls a function to clear the cache, which works fine (and I've tried just deleting the cache files manually anyway). Then it checks if we are even caching, i.e. if cache time is greater than 0. Then it uses the BASE64-encoded REQUEST_URI (under which name the file would have been cached previously) to check if a file with that name still exists in the cache dir, and if so loads it. Now, this works perfectly with a url like: mysite/myscript/mysubpage But when the page has parameters, like: mysite/myscript/mysubpage?search=widgets the file_exists function returns TRUE, even though the directory is empty. I did do a clearstatcache(); but it made no difference and anyway, it wouldn't explain why the URI with query string would fail while the regular one would not. And even if something is wrong with my code elsewhere, the fact is it is returning TRUE for a non-existent file. Can someone prevent my slide into insanity?! Here is my code so far (I say it's PDO but it pretty much isn't. What is the object here? The database connection? LOL!); $sql = " SELECT SUM(IF(`sent` != 'N' , 1 , 0 )) as 'Emails Sent', SUM(IF(`completed` NOT IN('N','paper') , 1 , 0 )) as 'Completed Electronically', SUM(IF(`completed` = 'paper' , 1 , 0 )) as 'Completed Manually', SUM(IF(`completed` != 'N' , 1 , 0 )) as 'Total Number Completed', SUM(IF(`remindercount` = '1' , 1 , 0 )) as 'Reminder Sent Once', SUM(IF(`remindercount` = '2' , 1 , 0 )) as 'Reminder Sent Twice', SUM(IF(`remindercount` = '3' , 1 , 0 )) as 'Reminder Sent Thrice' FROM `tokens_$survey_id` "; $statement = $dbh->prepare($sql); $statement->execute(); $result = $statement->fetch(PDO::FETCH_OBJ); foreach($result as $key => $value) { echo "<tr> <td>$key</td> <td>$value</td> </tr>"; }This is all well and good if the tokens_$survey_id table is actually there. Sometimes, for a genuine reason, there won't be a tokens table for that particular survey. How do I account for this? At the moment I get an error.. Warning: Invalid argument supplied for foreach() in /var/www/html/index.php on line 149I tried this but I am not satisfied this is correct; if(!$result) { die(); }I don't want the code to die! If I take out the die() statement then this if is ignored for some reason I don't understand. Hello fellow developers, Let me start by saying I'm still a PHP noob so please don't go too hard on me if I my code reflects this noobishness... So I'm trying to build a (very) simple RSS reader using jQuery and PHP. When the user clicks on an option from a dropdown, an AJAX call is made and passes the url selected from the list to a PHP script. The PHP script then loads the appropriate xml file from an 'xmlcache' folder. Everything is working just fine for files named as such: somefilename_1231231231.xml The problem is that I need it to be able to load files which have been urlencoded such as: http%3A%2F%2Ffeeds.feedburner.com%2Fajaxian_1235523548 In case you're wondering, the numbers at the end are a timestamp which will determine if the reader will load a cached copy of the desired xml file (if it's less than an hour old) or if it needs to get a fresh version (this part of the code is not written yet). Here is a look at my script thus far: <?php $url = "./xmlcache/" . urlencode($_REQUEST['url']); //access url from AJAX call echo $url; //outputs -> "./xmlcache/http%3A%2F%2Ffeeds.feedburner.com%2Fajaxian_1235523548.xml", which is the same as the file's name $curTime = time(); $urlParts = explode('_', $url); $urlTime = intval($urlParts[1]); $diff = $curTime - $urlTime; $urlAge = 60 * 60; //60sec * 60min = 3600sec or 1 hour if(file_exists($url)){ if($diff > $urlAge){ //the > will be switched to < to make logical sense once testing is done. $xml = simplexml_load_file($url); //ROOT TAG foreach($xml as $key0 => $value){ echo "$key0: $value"; foreach($value->attributes() as $attributeskey0 => $attributesvalue1){ echo "$attributeskey0: $attributesvalue1"; } echo "<br />"; //1 LEVEL BELOW ROOT TAG foreach($value as $key => $value2){ echo "$key: $value2"; foreach($value2->attributes() as $attributeskey => $attributesvalue2){ echo "$attributeskey = $attributesvalue2"; } echo '<br />'; //2 LEVELS BELOW ROOT TAG foreach($value2 as $key2 => $value3){ echo "$key2: $value3"; foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){ echo "$attributeskey2 = $attributesvalue3"; } echo '<br />'; //3 LEVELS BELOW ROOT TAG foreach($value3 as $key3 => $value4){ echo "$key3: $value4"; foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){ echo "$attributeskey3 = $attributesvalue4"; } echo '<br />'; //4 LEVELS BELOW ROOT TAG foreach($value4 as $key4 => $value5){ echo "$key4: $value5"; foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){ echo "$attributeskey4 = $attributesvalue5"; } echo '<br />'; //5 LEVELS BELOW ROOT TAG foreach($value5 as $key5 => $value6){ echo "$key5: $value6"; foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){ echo "$attributeskey5 = $attributesvalue6"; } echo '<br />'; } } } } echo '<br />'; } echo '<br />'; } }else{ //need to create the XML file from scratch, do a curl function, or read from a text file echo "need a new version"; //@unlink("$url); } }else{ echo "That file does not exist.<br/>"; } ?> The error message I'm getting is this: Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "./xmlcache/http%3A%2F%2Ffeeds.feedburner.com%2Fajaxian_1235523548.xml" in C:\wamp\www\reader\loadfeed.php on line 13 Warning: Invalid argument supplied for foreach() in C:\wamp\www\reader\loadfeed.php on line 16 The second error is obviously thrown because the file doesn't get loaded. I appreciate any help you gurus have to offer, and if you have any suggestions for the best way to load a fresh version that will be handled by the first else statement, I'm all ears. Thanks guys! Delete. I'm printing some mysql results to a table and sometimes I have rows with no results so they never get counted... which results in an ugly looking parenthesis on my page with nothing it (). For these times, I'd like to print a zero. How can I rewrite the following to achieve this? Code: [Select] if($row['mycount'] does not exist) { $row['mycount'] = '0'; } I guess I'm just stupid cause it seems like every time i get stuck and i post on here and its gets answered in less than 30 min.'s and i keep getting stuck! Here my script... function scoring($user){ $query = "SELECT Game_ID, Pick FROM Cfb WHERE User_ID= 1"; $result = mysql_query($query); $query1 = "SELECT Game_ID, Pick FROM Cfb WHERE User_ID= $user"; $result1 = mysql_query($query1); $affected = mysql_num_rows($result); for($i=0; $i< $affected; $i++) { $scores =mysql_fetch_assoc($result); $scores1 =mysql_fetch_assoc($result1); $main = array_diff_assoc($scores,$scores); $me = array_diff_assoc($scores, $scores1); $m = count($me); $m1 = count($main); if ($m == $m1){ $points += 1; }else{ $points += 0; } } echo '<br />'; echo '<br />'; echo $user; echo '<br />'; echo $points; echo '<hr />'; } $sql="SELECT id FROM users WHERE approved=1 AND user_level !=10"; $result=mysql_query($sql); while($row = mysql_fetch_object($result)) { $ids[] = $row->id; } print_r($ids); Alright heres what this script does... The script has a function that scores 1 individual user for his/her choices. Then I'm getting the user_ids from the users table at the bottom. Taking those and plugging them back into the function to score all the users at one time. Problem... Not all users will make picks. So how do i break the script in the function if that user_id is not is the CFB table attached to picks I have 2 tables im using Cfb and users users controls user info such as id # name username ect.. Cfb controls the picks. When a user makes there selection it stores there User_ID, Game_ID, and Pick So not all user ids are in the Cfb table. So if the script tries to input a user id thats not in the Cfb table it needs to break. Right now it just screws everything up! So how can i make it break that way? Thanks for any help Hi, No matter what I seem to change in my code, I sill get the same error! "Table 'suvoocom_wl.beta' doesn't exist" This is my 'core.php' file; Code: [Select] <?php session_start(); @include ('config.php'); @include ('connect.php'); // ######################################################################### // Check if Writing Lounge is under maintenance, and avoid, if possible $qry="SELECT * FROM fuse_rights WHERE username='".$_SESSION['username']."'"; $result=mysql_query($qry); if($result) { if(mysql_num_rows($result) == 1) { $checks = mysql_fetch_assoc($result); $am = $checks['avoid_maintenance']; } } if(isset($_SESSION['username']) && $am == 0) { $result = mysql_query("SELECT * FROM break") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { if($row['on'] == 1) { header('location:../maintenance'); exit(); } } } if(isset($_SESSION['username']) && $am == 1) { } else { $result = mysql_query("SELECT * FROM break") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { if($row['on'] == 1) { header('location:../maintenance'); exit(); } } } // ######################################################################### // Check if Writing Lounge has BETA activated if(!session_is_registered(betaaccess)){ $result = mysql_query("SELECT * FROM beta") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { if($row['on'] == 1) { header('location:../BETA'); exit(); } } } // ######################################################################### // Check if the user logged in is banned $result = mysql_query("SELECT username FROM bans WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); if (mysql_num_rows($result) > 0) { header('location:../banned'); exit(); } // ######################################################################### // Define the variables Writing Lounge will use later on $remote_ip = $_SERVER[REMOTE_ADDR]; $H = date('H'); $i = date('i'); $s = date('s'); $m = date('m'); $d = date('d'); $Y = date('Y'); $j = date('j'); $n = date('n'); $today = $d; $month = $m; $year = $Y; $date_normal = date('d-m-Y',mktime($m,$d,$Y)); $date_reversed = date('Y-m-d', mktime($m,$d,$y)); $date_full = date('d-m-Y H:i:s',mktime($H,$i,$s,$m,$d,$Y)); $date_time = date('H:i:s',mktime($H,$i,$s)); $date_hc = "".$j."-".$n."-".$Y.""; $regdate = $date_normal; $forumid = strip_slashes($_GET['id']); ?> It's basically the backbone to my website. This is my 'config.php' file; Code: [Select] <?php $sqlhostname = "localhost"; $sqlusername = "suvoocom_wl"; $sqlpassword = "*****"; $sqldb = "suvoocom_wl"; ?> And this is my 'connect.php' file; Code: [Select] <?php mysql_connect("$sqlhostname", "$sqlusername", "$sqlpassword")or die("Unable to connect."); mysql_select_db("$sqldb")or die("Unable to select the database you provided. Either I do not have premission to connect to that database, or the database doesn't exist."); ?> Does anyone have any ideas? :S Thanks! First time post, be easy on me...
I'm using preg_match_all to return an array with all the matches. I know I'm missing something fundamental, but I either keep looking past it or am more screwy than I know.
Sample String
CC-BY-ND-NCI'm using the following code preg_match_all("/cc|creative commons|copyright|by|sa|nc|nd/i",$exifmeta['copyright'],$cmeta)I would expect to see Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC ) )What I get is Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC [4] => sa ) ) Hi, My site was working fine, but I just switched servers/web hosts and now I'm getting the following errors (in blue). The thing is, I don't get the error if I try to run the query loop after just using 'mysql_select_db' once, but if I use it again to select a different database and then run the query loop, I start getting the error. Code: [Select] mysql_select_db ("database1", $mysql_con); $mysql_query = mysql_query ("SELECT ID FROM someTable1", $mysql_con); $someVar1 = 0; while ($mysql_array = mysql_fetch_array ($mysql_query)) { $someVar1 ++; } ////// The above code gives me no error. But If I then try to select a different database and run a loop in the same way (in the same file), I start getting the below error... mysql_select_db ("database2", $mysql_con); $mysql_query = mysql_query ("SELECT ID FROM someTable2", $mysql_con); $someVar2 = 0; while ($mysql_array = mysql_fetch_array ($mysql_query)) { $someVar2 ++; } Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/snubby5/public_html/coozymcmillan.com/view.php on line 86 So I looked it up and somewhere it told me to add some extra code to handle errors better: Code: [Select] if ($mysql_query === FALSE) { die (mysql_error ()); // TODO: better error handling } But when I do that, I get a different error: Table 'database1.someTable2' doesn't exist It doesn't seem to recognize that I switched databases, and it says 'database1.someTable2' doesn't exist (because it doesn't), when really it should be checking for 'database2.someTable2' (which exists). So to reiterate, I can run the query loop fine after selecting database1, but after that if I select database2, it either gives me the first error, or If I add the 'die' code it gives me the second error. Thanks much! PS: I can get it working if I put everything into one database, but I have multiple websites (which sometimes need to call eachothers' databases) and it would be a huge hassle to cram them all into one database unless I have to. Hi all, I want to make a script that identifies if an image JPG file exists. Would somthing like this work? <?php $file = "images/image.jpg"; if ($file > 0) { echo "file exists"; } else { echo "no file"; } ?> Hi everyone, I'm still learning, but getting intermediate in PHP now, but it is still challenge to learn. I'm trying to have php check to see if one file inside folder in server, seem I could not get it right, but I tested it on other site, it works, but not this script, I don't understand why it won't work...maybe logical is wrong? here my code: if ($_POST['video']) { $path1 = "UPLOADS/Home/"; $path2 = "UPLOADS/Breakfast/"; $path3 = "UPLOADS/Spider/"; $scan1 = scandir($path1); $scan2 = scandir($path2); $scan3 = scandir($path3); $count1 = count($scan1) - 3; $count2 = count($scan2) - 3; $count3 = count($scan3) - 3; if($count1 > 0) { header('location:exist.html'); }elseif ($count2 > 0) { header('location:exist.html'); }elseif ($count3 > 0) { header('location:exist.html'); } But other site, it works: $scan = scandir($path); $count = count($scan) - 3; echo $count; if($count > 1){ echo "Hello yourself!<br />"; } Anyone will help will be appreciate! Thank you! Gary Edited April 3, 2019 by sigmahokiesi have error where my code should update existing data where id exist, it get updated ..but the others data is disappeared .only the data updated is remained $sql1 ="select*from semakan_dokumen where email='$stdEmail'"; $sqlsearch1 = mysqli_query($dbconfig,$sql1); $resultcount1 = mysqli_num_rows($sqlsearch1); if($resultcount1 > 0){ $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3',sijil_sekolah= '$fileName4', sijil_dip= '$fileName5',sej_julai='$fileName6',bm_julai='$fileName7',muet='$fileName8', mid1='$fileName9',yuran= '$fileName10',umpa_bend1= '$fileName11',umpa_bend2='$fileName12',bpkp='$fileName13', penaja='$fileName14',kesihatan= '$fileName15', jhepa='$fileName16' where email= '$stdEmail' "); }else{ //filezip $query1 = "INSERT INTO semakan_dokumen (email,surat_tawaran,ic,sijil_lahir,sijil_spm,sijil_sekolah,sijil_dip,sej_julai,bm_julai,muet,mid1,yuran,umpa_bend1,umpa_bend2,bpkp,penaja,kesihatan,jhepa) VALUES ('$stdEmail','$fileName','$fileName1','$fileName2','$fileName3','$fileName4','$fileName5','$fileName6','$fileName7','$fileName8','$fileName9','$fileName10','$fileName11','$fileName12','$fileName13','$fileName14','$fileName15','$fileName16')"; }
My first stab at connecting to an API with php. The API takes a url and returns an xml file. When I try this: <?php $apicall = "https://www.graphicmail.com/api.aspx?Username=dyates@salemharvest.org&Password=x&Function=get_newsletters&SID=0"; $xml = simplexml_load_file($apicall); print_r($xml); ?> My local testing server responds with: Warning: simplexml_load_file() [function.simplexml-load-file]: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? However, in the php configuration file, php.ini, I have: 'allow_url_fopen = On' which is what the manual says is all you need for https use in most functions that take urls. The url that is $apicall works correctly when just pasted into the browser. When I try the php code on the production server I get no warning (they are turned off) and no output. Any ideas? Hi.
I am trying to fetch xml from a betting website feed. The feed is restricted per IP but I have had the server IP, where the site is located, whitelisted and they have confirmed numerous times that the IP has definitely been whitelisted.
If I try to connect using simplexml_load_file to a BBC xml feed it works fine but to the betting feed I get "failed to open stream: HTTP request failed!"
Is there any way of knowing why it is failing or is there anything else that could prevent it from connecting to that specific feed?
many thanks in advance
Sam
first off I have to make an empty loc.xml file with permissions in order to write contents, I understand the permission idea. secondly, simplexml_load_file does nothing I get it straight from here http://us2.php.net/manual/en/function.simplexml-load-file.php <?php $request='http://z3950.loc.gov:7090/voyager?version=1.1&operation=searchRetrieve&query=dinosaur&startRecord=2&maximumRecords=5'; //echo $request; $filename = dirname(__FILE__)."/loc.xml"; $raw_xml = file_get_contents($request); //echo $raw_xml; $fp = fopen($filename, "w"); fwrite($fp, $raw_xml); fclose ($fp); // The file test.xml contains an XML document with a root element // and at least an element /[root]/title. if (file_exists($filename)) { $xml = simplexml_load_file($filename); print_r($xml); } else { exit('Failed to open loc.xml.'); } ?> Does the file have to be in the document root? If not, what is the correct syntax to point simplexml_load_file() to a directory on the server that is not the document root? ie what goes between the () this works fine if the .xml file is in my public html root - simplexml_load_file('sample.xml') but when I put the file in a different directory on the server, I can't figure out how to point to it. Help is appreciated. I have an application that loads several xml files, and then outputs some of the data from the file. The problem is that every once in a while, the service that provides the xml file does maintenance (or has an error in the file), and my application gives a "Fatal error: Call to a member function children() on a non-object in..."
I would like to handle the error differently, by displaying "unavailable" instead of the error. I know that this is usually not the appropriate way of handling errors, because there is a reason for a fatal error.
Any ideas on how to appropriately handle this error?
// Node 217 (GGB) $xml = simplexml_load_file("http://services.my511.org/traffic/API_KEY_REMOVED_FOR_EXAMPLE"); foreach($xml->children() as $traveltime) { $ggb = "$traveltime->currentTravelTime"; } echo "GGB:" , $ggb , " Minutes"; Why doesn't it add a new line when I open up index.php Code: [Select] $fp = fopen('text.txt','w'); fwrite($fp, "Your IP: ".$_SERVER['REMOTE_ADDR']."\n"); fclose($fp); |