Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP If file_get_contents fails, do this instead

Tags:

php

I have a function to translate the current text string using the Free Bing translator API. I just want to make sure if anything fails or something happens with the Application ID or I go over on requests, I don't want a big error to show.

The code I have right now is:

$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$translate = simplexml_load_string($translate_feed);

return $translate[0];

What I want to happen is if anything fails, so if I add in another character to the URL to make it invalid then I want it to just return $text so at least something shows.

Thanks!

like image 574
Drew Avatar asked Dec 29 '11 20:12

Drew


People also ask

Which is faster cURL or file_get_contents?

cURL is capable of much more than file_get_contents . That should be enough. FWIW there's little difference with regards to speed. I've just finished fetching 5,000 URLs and saving their HTML to files (about 200k per file).

What will the file_get_contents () return?

The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What is the function file_get_contents () useful for?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.

What is the difference between file_get_contents ($ file and file_get_contents ($ file in PHP?

2 Answers. Show activity on this post. The first two, file and file_get_contents are very similar. They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string.


3 Answers

You can do like this

if(@file_get_contents("yourFilePath.txt")){
     echo "success";
}
like image 174
Azam Alvi Avatar answered Oct 24 '22 04:10

Azam Alvi


$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');


if ( $translate_feed === false )
{
   echo "failed";
}
like image 28
Wes Crow Avatar answered Oct 24 '22 02:10

Wes Crow


Have you tried failing it on purpose to see what happens?

If it's an exception, just catch it and handle it...

try{
    //enter code to catch
}catch(Exception $ex){
    //Process the exception
}

If there is an error outputted by the function, just @ to hide the error and handle the incorrect output of $translate_feed or $translate manually.

You can try failing it on purpose by simply passing an invalid URI to file_get_contents and then forcefully feed non XML or invalid XML to simplexml_load_string to see what happens.

like image 37
Mathieu Dumoulin Avatar answered Oct 24 '22 04:10

Mathieu Dumoulin