Reading simple API returns blank screen? - php

For some reason I cannot figure out how to fix this online anywhere? I have this simple free chuck norris joke api that I'm simply trying to output the json of, but it wont work? I just get a blank screen?
In the console the network tab says 200 ok and that the headers are valid? What am I doing wrong?
My code:
<?php
header('Content-Type: application/json');
header('X-RapidAPI-Host: matchilling-chuck-norris-jokes-v1.p.rapidapi.com');
header('X-RapidAPI-Key: 341b5c1156msh6827bf7184ef4ddp1c8d09jsnbc52db5d01be');
$str = file_get_contents('https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random');
// decode JSON
$json = json_decode($str, true);
// get the data
print_r($json);

Most likely you want to send those headers...
header prints out the headers to you, locally, where you execute it.
With file_get_contents it will be like this:
<?php
$opts = [
"http" => [
"method" => "GET",
"header" => "Content-Type: application/json\r\n" .
"X-RapidAPI-Host: matchilling-chuck-norris-jokes-v1.p.rapidapi.com\r\n" .
"X-RapidAPI-Key: 341b5c1156msh6827bf7184ef4ddp1c8d09jsnbc52db5d01be\r\n"
]
];
$context = stream_context_create($opts);
$str = file_get_contents('https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random', false, $context);
// decode JSON
$json = json_decode($str, true);
// get the data
print_r($json);
I also kindly suggest switching to curl extension.

Related

Setting correct content type for cURL to receive a response

I'm trying to create a relatively simple PHP endpoint for users to send requests to. I know that the endpoint is working because when I accessed it using cURL the parameters I sent to my database we're added. The problem however is that when I use
var_dump($response);
The page returns "NULL".
So the code is working fine, I just want to know how to print an error/success message
This is what I've tried so far on the endpoint
header("HTTP/1.1 200 OK");
header('Content-Type: text/plain');
echo 'Success message';
the full cURL code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
);
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = json_decode($resp, true);
var_dump($response);
So how can I get the success message to properly show instead of "NULL"?
Test if your curl code returns something by testing: var_dump($resp). It looks like NULL comes from json_decode. You are not returning valid JSON from the endpoint.
php > var_dump(json_decode("Success message", true));
NULL
Try returning a json string such as:
php > echo json_encode("Success", true);
"Success"
Note the " around it. This encodes a json string. See the JSON spec for a reference on how to encode json. Best practice, if your return json, then run your content through json_encode().
Your curl code seems correct.

Formatting JSON Data using PHP

I have the following code:
<?php
$ids = 'ids=com.hugogames.hugotrollwars';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $ids
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://play.google.com/store/xhr/getdoc', false,
$context);
$convert = explode("\n", $result);
Basically its pulling permissions from the Playstore and displaying it as a string. The issue I am having is removing the un needed data (image links, description) and only show the permissions and the permissions description. I tried using the json_decode function with php and it returned NULL.
Is there something i'm missing?
Any help is greatly appreciated!
$result is not valid json. Google Play API is using a protobuf variant.
http://www.segmentationfault.fr/publications/reversing-google-play-and-micro-protobuf-applications/
There are also php libraries to talk to google play.
https://github.com/splitfeed/android-market-api-php
https://github.com/thetutlage/Google-Play-Store-API

PHP json_encode adds some number (hex?) to the beginning of the json-string

I am echoing json_encoded data from one php script to another (the request is made by fsockopen/GET).
When having encoded an array with 40 elements, there is no problem. When doing exactly the same thing with 41, some numbers and \r\n is added to the beginning of the json string.
This is the beginning of the string just before I echo it:
{"transactions":[{"transaction_id":"03U191739F337671L",
This is how I send the data:
header('Content-Type: text/plain; charset=utf-8');
error_log(json_encode($transaction_list));
echo json_encode($transaction_list);
As soon as I have received the data in the requesting script I print it again to error_log:
27fc\r\n{"transactions":[{"transaction_id":"03U191739F337671L",
The "27fc\r\n" is not there if I retrieve less data.
This is how I handle the response:
$response="";
while (!feof($fp)) {
$response .= fgets($fp, 128);
}
//Seperate header and content
$separator_position = strpos($response,"\r\n\r\n");
$header_text = substr($response,0,$separator_position);
$body = substr($response,$separator_position+4);
error_log($body);
fclose($fp);
I have tried playing around with the time out of the fsockopen request, that doesn't matter. The same thing with max_execution_time and max_input_time in php.ini, doesn't matter. I was thinking that the content in some way may have been cut due to time out...
The 41st array is having no different format of the content than the preceding ones.
What is happening and how can I fix it?
I am using Linux, Apache (httpd) and PHP.
UPDATE
The data seems to be chunked. In the response, following header is included: "Transfer-Encoding: chunked".
Based on #Salmans idea of using file_get_contents, this is the working solution. This uses POST to send the data (GET didn't seem to be working, I think one has to append that query string to the URL oneself):
$postdata = http_build_query(
array('customer_id' => $customer_id)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$content = file_get_contents($my_url, false, $context);
return $content;

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.

Getting JSON response with PHP

I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>

Categories