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 Applicat
if( !$translate_feed) return "Failed";
$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";
}
there is $http_response_header variable is being created in local scope that we can use it to check headers returned from server. Here is my implementation:
public function getData($url)
{
try {
$response = @file_get_contents($url);
if (isset($http_response_header)) {
if (!in_array('HTTP/1.1 200 OK', $http_response_header) &&
!in_array('HTTP/1.0 200 OK', $http_response_header)) {
throw new \Exception('Server did not return success header!');
}
}
return $response;
} catch (\Exception $ex) {
throw new TransportException($ex->getMessage(), $ex->getCode(), $ex);
}
}
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.
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$result=$text;
if ($translate_feed) {
$translate = simplexml_load_string($translate_feed);
if (is_array($translate)) $result=$translate[0];
}
return $result;
You can do like this
if(@file_get_contents("yourFilePath.txt")){
echo "success";
}