what is the PHP equivalent for API Python's requests package - php

I am trying to replicate the same json request in php from this Python code:
import requests
url = 'http://site.api.espn.com/apis/site/v2/sports/football/college-football/scoreboard'
payload = {
'limit':'500',
'groups':'8'}
jsonData = requests.get(url, params=payload).json()
I know how to curl a API request in php but not sure the sythanx for the parameter input, in this case , 'limit' & 'groups'

Use http_build_query() to convert the array of parameters to URL query parameters, then concatenate it to the URL.
file_get_contents() is the simple equivalent to requests.get() if you don't need to provide any custom headers.
$payload = [
'limit' => 500,
'groups' => 8
];
$params = http_build_query($payload);
$url = 'http://site.api.espn.com/apis/site/v2/sports/football/college-football/scoreboard?' . $params;
$result = file_get_contents($url);
$json_data = json_decode($result, true);

Related

how to make multiple api call at the same time?

CoinMarketCap Api offer a lot of data by making calls to different links. Every time you make a call it cost 1 credit and of course, if that call return 5,000 coins then it cost 25 credits. So, I can't make call to different link every minute. How can I make a call to at least 4 links such as:
https://pro-api.coinmarketcap.com/v1/cryptocurrency/trending/latest
https://pro-api.coinmarketcap.com/v1/cryptocurrency/trending/gainers-losers
https://pro-api.coinmarketcap.com/cryptocurrency/listings/latest?limit=5000
https://pro-api.coinmarketcap.com/v2/cryptocurrency/info
and here is the code that CoinMarketCap offer and it works (tested):
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';
$parameters = [
'start' => '1',
'limit' => '5000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: *********-****-****-****-***********'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
//Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
you can use the curl_multi_init to handle the multiple curl request asynchronously. you can read here more about multi curl

how to get information from url into variable

So i'm trying to get location usng reverse geocoding
https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
so my question is (since i'm very new to php) how to get the result from URL into parameter (the result will be json encoded data)
you can use function file_get_contents to get Data from URL
$API_KEY ="XXXXXXX";
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=".$API_KEY;
$data = #file_get_contents($url);
$jsondata = json_decode($data,true);
if(is_array($jsondata) && $jsondata['status'] == "OK")
{
echo '<pre>'; print_r($jsondata);echo '</pre>';
}
To get the data we use the PHP curl functions.
[php]
// jSON URL which should be requested
$json_url = ‘www.yourdomain.com';
$username = ‘your_username'; // authentication
$password = ‘your_password'; // authentication
// jSON String for request
$json_string = ‘[your json string here]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . “:” . $password, // authentication
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
[/php]
The result will be a jSON string.
Normally you have to send a jSON string to the jSON URL and you will get a jSON string back. To encode your data, just use the php jSON functions. Use json_encode to create a json string from your PHP array and use json_decode to transform the jSON string to PHP array.

Google Closure, Response Always Empty

I'm trying to get together a basic example of how to use Google Closure to minify JS. I can't seem to get this to work at all.
I'm trying to follow these examples:
https://developers.google.com/closure/compiler/docs/gettingstarted_api
http://closure-compiler.appspot.com/home
When working on API's and/or AJAX code, the first thing I try to is get the variables and values setup properly using just Advanced Rest Client Applications - a Chrome Extension. Whenever I send this data, though, I get an empty response (image below).
Trying to insert the same code into my PHP code, no matter what I send in the $postData variable, I get an empty (null) response.
PHP Code:
$postData =
http_build_query(
[
'output_info' => 'compiled_code',
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'js_code' => urlencode("function hello(name) { // Greets the user alert('Hello, ' + name); } hello('New user');")
]
);
$ret = $this->ci->curl->simple_post(
$url,
$postData,
$options
);
var_dump($ret);
die();
Response:
string ' ' (length=1)
I'm 99% confident that I'm missing something to use the Closure API like a key or something, but I have no idea how to proceed.
After many, many, many attempts, I found that if I used rawurlencode() instead of urlencode(), it works. Here's the final function.
// use google closure to get compiled JS
$encoded = rawurlencode($js);
$postData =
'output_info=compiled_code&' .
'output_format=text&' .
'compilation_level=WHITESPACE_ONLY&' .
'js_code=' . $encoded
;
$options = [];
$call = curl_init();
curl_setopt_array(
$call,
array(
CURLOPT_URL => 'http://closure-compiler.appspot.com/compile',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_FOLLOWLOCATION => 0
)
);
$jscomp = curl_exec($call);
return $jscomp;

Can't send data in post request via file_get_contents

Need to request some code two times in my app. Fist request url as ajax call, and also need to request this url in controller (something like hmvc). I know how to develop this via curl but I found another kind of idea how to implement this, just use function file_get_contents with before prepared params. This my code:
// Setup limit per page
$args['offset'] = $offset;
$args['limit'] = $this->_perpage;
// --
// Convert search arguments to the uri format
$data = http_build_query($args);
// Define request params
$options = array(
'http' => array(
'header' => 'Content-type: application/json' . PHP_EOL .
'Content-Length: ' . strlen($data) . PHP_EOL,
'method' => 'POST',
'content' => $data,
),
);
$context = stream_context_create($options);
$result = file_get_contents(
'http://'.$_SERVER['HTTP_HOST'].'/search/items', FALSE, $context
);
Request method was detected ok in requested uri, but params wasn't passed. Why this is not pass arguments to request? Where is bug in my code? Many thanks for any answers.
http_build_query builds application/x-www-form-urlencoded content. (not application/json)
There is a full example:
How to post data in PHP using file_get_contents?
Content type should be application/x-www-form-urlencoded. If you want to stay with application/json, try to get posted data using file_get_contents("php://input").

Api in PHP - Accept a curl request and process

Not sure if anyone can help me out with a question.
I had to write some php for the company I work for that lets us integrate with an API that accepts a JSON body. I used the cUrl method, and the script is working great.
If I wanted to build another php page that would accept the request im sending, how would I go about this?
Say I wanted to allow someone to send this same request to me, and then wanted the info they sent to go into my database, how would turn their request into php strings?
Here is the code im sending.
<?
$json_string = json_encode(array("FirstName" => $name, "MiddleName" => " ", "LastName" => $last));;
// echo $json_string;
// jSON URL which should be requested
$json_url = 'http://www.exampleurl.com';
// jSON String for request
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Accept: application/json;charset=utf-8',
'Content-Type: application/json;charset=utf-8',
'Expect: 100-continue',
'Connection: Keep-Alive') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
echo $result;
$myArray = json_decode($result);
$action = $myArray->Action;
?>
To get the raw data from the POST that you would be receiving you would use $postData = file_get_contents('php://input');
http://php.net/manual/en/reserved.variables.post.php
Then you would json_decode() the contents of that POST back into JSON.
http://php.net/manual/en/function.json-decode.php
Not really good understood your question. May be you are looking for the way to read raw POST data? In that case open and read from php://stdin stream.
$stdin = fopen('php://stdin', 'r');
By the way read here ( http://php.net/manual/en/function.curl-setopt.php ) how to use CURLOPT_POSTFIELDS. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.

Categories