I want get json from a url with file_get_contents but it replace & with & and it dosnt work this way
i tried curl and happened again
i try url directly too and it worked ,so url haven't problem
$url="https://api.kavenegar.com/v1/asdkljsadlkjsd/sms/send.json?receptor=09148523669&sender=100005252&message=testing";
$json = file_get_contents($url);
echo "1";
var_dump($json);
and this is the result:
( ! ) Warning:
file_get_contents(https://api.kavenegar.com/v1/asdkljsadlkjsd/sms/send.json?receptor=09148523669&sender=100005252&message=testing):
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in C:\wamp64\www\te\func\testjson.php on line 22
Of course stackoverflow remove & from result url.
The trouble seems to be that it's returning an error status code. If so then see:
Ignoring errors in file_get_contents HTTP wrapper?
$url="https://api.kavenegar.com/v1/asdkljsadlkjsd/sms/send.json?receptor=09148523669&sender=100005252&message=testing";
$context = stream_context_create(array('http' => array('ignore_errors' => true),));
$json = file_get_contents($url, false, $context);
echo $json;
this is the answer :
$url = 'https://example.url?';
// http_build_query builds the query from an array
$query_array = array (
'search' => $string,
'from' => $from,
'to' => $to,
'format' => 'json'
);
$query = http_build_query($query_array);
$result = file_get_contents($url . '&' . $query);
Related
im gonna use an api to get player details. Some names are with special characters.
Name Bausí
Url: https/eu.api.battle.net/wow/character/Blackrock/Bausí?fields=statistics&locale=en_GB&apikey=xxx
if i use file_get_contens() there is no response.
Names without special characters works perfectly. I already used rawurlencode() and urlencode(). Both are not working. What can i do?
I read something about urlencode() and rawurlencode() is server dependant.
Thanks Chzn
Well i dont know whats wrong.
$charname = mb_convert_encoding("Bausí", "HTML-ENTITIES", "UTF-8");
$realm = "Blackrock";
$_SESSION["region"] = "eu";
$opts = array('https' => array('header' => 'Accept-Charset: UTF-8, *;q=0'));
$context = stream_context_create($opts);
$char_params = array(
'fields' => "statistics",
'locale' => "en_GB",
'apikey' => "my_api_key"
);
$char_url = "https://".$_SESSION['region'].".api.battle.net/wow/character/".str_replace("'","",$realm)."/".$charname."?".http_build_query($char_params);
if (!$json_char_o = file_get_contents($char_url, false, $context)) {
$error = error_get_last();
echo "HTTPs request failed. Error was: " . $error['message'];
}else{
echo $json_char_decoded = json_decode($json_char_o);
}
it throws me an error:
HTTP request failed. Error was: file_get_contents(https://eu.api.battle.net/wow/character/Blackrock/Bausí?fields=statistics&locale=en_GB&apikey=my_api_key): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
The response should be a json object.
If i open the link manually it works perfectly. What is wrong? :/
I have a very simple script that works perfectly on most sites but not the main site I want it to work with - the code below accesses a sample site perfectly. However when I use it on a site I want to access http://www.livescore.com I get an error
This works.
<?php
$url = "http://www.cambodia.me.uk";
$page = file_get_contents($url);
$outfile = "contents.html";
file_put_contents($outfile, $page);
?>
This does not work.....
<?php
$url = "http://www.livescore.com";
$page = file_get_contents($url);
$outfile = "contents.html";
file_put_contents($outfile, $page);
?>
and gives the following error
Warning: file_get_contents(http://www.livescore.com)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 404 Not Found in C:\Program Files
(x86)\EasyPHP-5.3.8.1\www\Livescore\attempt-1-read-page.php on line 3
Thanks for any assistance
In common case you can just say to file_get_contents to follow redirects:
$context = stream_context_create(
array(
'http' => array(
'follow_location' => true
)
)
);
$html = file_get_contents('http://www.example.com/', false, $context);
This site tries to analyze User-agent http header, and fails if it's not found. Try to add some user-agent header:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "User-agent: chrome",
'ignore_errors' => true,
'follow_location' => true
)
)
);
$html = file_get_contents('http://www.livescore.com/', false, $context);
echo substr($html, 0, 200)."\n";
Most likely www.livescore.com is doing a hidden redirect which file_get_contents is too basic to catch.
Do you have lynx installed on your server?
$page= shell_exec("lynx -source 'http://www.livescore.com'");
lynx is a full browser and can 'bypass' certain redirects.
I have a html page which sends a get request to php.
This is the code snippet in the php file
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>'GET',
)
);
$context = stream_context_create($opts);
//echo("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token={$_GET['token']}&agencyName={$_GET['agency']}&stopName={$_GET['stopname']}");
// Open the file using the HTTP headers set above
$file = file_get_contents("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token={$_GET['token']}&agencyName={$_GET['agency']}&stopName={$_GET['stopname']}", false, $context);
//$file = file_get_contents("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token=123-456-789&agencyName=SF-MUNI&stopName=The%20Embarcadero%20and%20Folsom%20St", false, $context);
echo(json_encode(simplexml_load_string($file)));
?>
Developer Console Output :
Warning: file_get_contents(http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token=123-456-789&agencyName=BART&stopName=Powell St. (SF)): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST
As you can see from the developer console output, in the url request sent there are BART&stopName amp;amp; being inserted in the url which I'm not doing. The request fails due to this. Any solution around this?
Try the below code, this will make sure that you're stuff is properly URI encoded.
$params = [
'token' => $_GET['token'],
'agencyName' => $_GET['agency'],
'stopName' => $_GET['stopname']
];
$file = file_get_contents(sprintf("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?%s", http_build_query($params));
echo(json_encode(simplexml_load_string($file)));
Try this one:
$data = array('token'=>$_GET['token'],
'stopname'=>$_GET['stopname'],
'agency'=>$_GET['agency'],
);
$url = "http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?".$data;
$file = file_get_contents($url, false, $context);
echo(json_encode(simplexml_load_string($file)));
Note: I have modified my answer base on your comment.
You can try this way to clean out the url:
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>'GET',
)
);
$context = stream_context_create($opts);
$url= "http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?";
$query = array(
"token" =>$_GET['token'],
"agencyName"=>$_GET['agency'],
"stopName"=>$_GET['stopname']
);
$url = $url.http_build_query($query);
$url = rawurldecode($url);
print_r($url);
$file = file_get_contents($url, false, $context);
echo(json_encode(simplexml_load_string($file)));
?>
I'm trying to use file_get_contents together with stream_context_create to make POST requests. My code so far:
$options = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' =>
"Content-Type: text/plain\r\n" .
"Content-Length: " . strlen($data) . "\r\n"
));
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
It works fine, however, when an HTTP error occurs, it spits out a warning:
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
and returns false. Is there a way to:
suppress a warning (I'm planning to throw my own exception in case of failure)
obtain the error information (at least, the response code) from the stream
http://php.net/manual/en/reserved.variables.httpresponseheader.php
$context = stream_context_create(['http' => ['ignore_errors' => true]]);
$result = file_get_contents("http://example.com", false, $context);
var_dump($http_response_header);
None of the answers (including the one accepted by OP) actually satisfy the two requirements:
suppress a warning (I'm planning to throw my own exception in case of failure)
obtain the error information (at least, the response code) from the stream
Here's my take:
function fetch(string $method, string $url, string $body, array $headers = []) {
$context = stream_context_create([
"http" => [
// http://docs.php.net/manual/en/context.http.php
"method" => $method,
"header" => implode("\r\n", $headers),
"content" => $body,
"ignore_errors" => true,
],
]);
$response = file_get_contents($url, false, $context);
/**
* #var array $http_response_header materializes out of thin air
*/
$status_line = $http_response_header[0];
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
$status = $match[1];
if ($status !== "200") {
throw new RuntimeException("unexpected response status: {$status_line}\n" . $response);
}
return $response;
}
This will throw for a non-200 response, but you can easily work from there, e.g. add a simple Response class and return new Response((int) $status, $response); if that fits your use-case better.
For example, to do a JSON POST to an API endpoint:
$response = fetch(
"POST",
"http://example.com/",
json_encode([
"foo" => "bar",
]),
[
"Content-Type: application/json",
"X-API-Key: 123456789",
]
);
Note the use of "ignore_errors" => true in the http context map - this will prevent the function from throwing errors for non-2xx status codes.
This is most likely the "right" amount of error-suppression for most use-cases - I do not recommend using the # error-suppression operator, as this will also suppress errors like simply passing the wrong arguments, which could inadvertently hide a bug in calling code.
Adding few more lines to the accepted response to get the http code
function getHttpCode($http_response_header)
{
if(is_array($http_response_header))
{
$parts=explode(' ',$http_response_header[0]);
if(count($parts)>1) //HTTP/1.0 <code> <text>
return intval($parts[1]); //Get code
}
return 0;
}
#file_get_contents("http://example.com");
$code=getHttpCode($http_response_header);
to hide the error output both comments are ok, ignore_errors = true or # (I prefer #)
To capture the error message when file_get_contents returns FALSE, write a function which uses ob_start and ob_get_contents to capture the error message that file_get_contents writes to stderr.
function fileGetContents( $fileName )
{
$errmsg = '' ;
ob_start( ) ;
$contents = file_get_contents( $fileName );
if ( $contents === FALSE )
{
$errmsg = ob_get_contents( ) ;
$errmsg .= "\nfile name:$fileName";
$contents = '' ;
}
ob_end_clean( ) ;
return (object)[ 'errmsg' => $errmsg, 'contents' => $contents ];
}
I go to this page with kind of a different issue, so posting my answer. My problem was that I was just trying to suppress the warning notification and display a customized warning message for the user, so this simple and obvious fix helped me:
// Suppress the warning messages
error_reporting(0);
$contents = file_get_contents($url);
if ($contents === false) {
print 'My warning message';
}
And if needed, turn back error reporting after that:
// Enable warning messages again
error_reporting(-1);
#file_get_contents and ignore_errors = true are not the same:
the first doesn't return anything;
the second suppresses error messages, but returns server response (e.g. 400 Bad request).
I use a function like this:
$result = file_get_contents(
$url_of_API,
false,
stream_context_create([
'http' => [
'content' => json_encode(['value1' => $value1, 'value2' => $value2]),
'header' => 'Authorization: Basic XXXXXXXXXXXXXXX',
'ignore_errors' => 1,
'method' => 'POST',
'timeout' => 10
]
])
);
return json_decode($result)->status;
It returns 200 (Ok) or 400 (Bad request).
It works perfectly and it's easier than cURL.
I need to pass these headers into the $context variable, i tried using putting the values into an array and then passing it into stream_context_create() function but i get http warnings from the file_getcontents function
$prod_id = 4322;
$tnxRef = "RT45635276GHF76783AC";
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673";
$agent = $_SERVER['HTTP_USER_AGENT'];
$hash = hash('SHA512', $prod_id.$txnRef.$mackey);
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'$agent \r\n'.
'$hash'
)
)
stream_context_create($headers)
$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context);
$json = json_decode($url_returns, true);
Error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`
Thats the error i get, can somebody please help with a definitive example.
You have several errors in your code.
The server returns 400 Bad Request, because your code would result in this incorrect HTTP request:
GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1
Host: test_server.com
Content: type=application/json
$agent
$hash
The errors are:
Variable expressions are not evaluated within single quotes
$amount is not set in your code example
The header is Content-Type: and not Content: type=
All headers (agent, hash) must have their corresponding name
Here is an example that should work:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'agent' => $agent,
'header' => "Content-Type: application/json\r\n"
. "X-Api-Signature: $hash"
)
)
);
Please note: X-Api-Signature is just an example - it depends on the API you are using how the API key header is named and how the hash is calculated. You should find this information in the Docs of your API!