PHP Get REST Api and parse JSON - php

I have done research and I can't seem to find a solution. I have a website running XenForo and added XenAPI to the Software.
When you call the API: ( api.php?action=authenticate&username=USERNAME&password=PASSWORD)
it returns the following JSON:
{
"hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
}
I am trying to find the "proper" way of capturing the JSON and decoding it. I hope you guys can help! Note that I am looking for a example to learn from, because all other examples fail.

For simple requests with 1-2 params, you can use
$json = file_get_contents(url...);
$response = json_decode($json, true);
For more difficult queries use curl extension.
For full web-applications use Guzzle - curl wrapper for communicates with API.

Related

PHP cURL response returning a string, how do I handle and select from the data?

I'm using a Codeigniter curl library to do a simple get request to a url. When I echo the response, it's coming back as a string. I can't quite figure out what I can do to convert that string into a useable format, because I need to be selecting from specific parts of the return to progress in my function.
My code is ran through Codeigniter, using Philsturgeon's curl library, here's a simple example of what I'm using:
$this->load->library('Curl');
$response = $this->curl->simple_get('https://api.twitch.tv/kraken/channels/username');
var_dump($response);
I feel like I'm missing something simple here. Any help?

file_get_contents doesn't respond

I'm trying to get a JSON string from a page in my Laravel Project. Using this:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
return View::make('adventuretime.marceline')
->with('json', $json)
->with('title', 'ICE KING')
->with('description', 'I am the Ice King')
->with('content', 'ice king');
But since I'm only using a localhost, I think this doesn't work that's why it doesn't output anything. I want to know what is the proper way for it to be flexible and be able to get the JSON string with any $url value using php?
Looking at the comments above, it is possible that the $url you are using is not valid, check it out by pointing your browser there and see what happens.
If you are sure that the $url is fine, but you still get the 404 Not Found error - verify that you have proper Laravel routing defined for that address. If the routes are fine, maybe you forgot to do
composer dump-autoload
after making modifications in your routes.php. If so, try the above and refresh the browser to see if it helps.
Furthermore, bear in mind that using your current function, you can submit only GET requests. What is more, this function might not be available for fetching remote urls, on some hosting servers due to security reasons. If you still want to use it, it'd be good to check
if($json !== FALSE)
before you process the $json response. If the file_get_contents fails it will return false.
Reffering to the part of your question
what is the proper way for it to be flexible and be able to get the JSON string with any $url
I'd suggest using cURL, as a standard and convenient way to fetch remote content. Using cURL you have better control over the process of sending the http request and receiving the "answer" it returns. Personaly, in my Laravel 4 apps I often use this package jyggen/curl. You can read the docs for it here: jyggen docs
If you are not satisfied with cURL and you want greater control try Guzzle As the authors state, Guzzle is a PHP HTTP client & framework for building RESTful web service clients.

Pinterest API - pure json response?

So I made a simple HTTP request to Pinterest's API to get the count of a link:
$this->load->library('rest');
$this->rest->initialize(array('server' => 'http://api.pinterest.com/'));
$return_data = $this->rest->get('v1/urls/count.json?callback=&url=' . $link);
The response I get is:
receiveCount({"count": 5743, "url": "http://google.com"})
You can try this yourself here.
I don't want the callback and I tried setting callback= but the parenthesis are still present so I can't parse it via json_decode.
Is there a better way of getting a pure json response without having to string replace the parenthesis myself?
The Pintrest API is currently in development and is not ready for public use; they removed their own documentation a while ago. There is however a cache on Bolt for v2 of the API.
For now I would just do a regex on the response such as
$return_data = preg_replace('/^receiveCount\((.*)\)$/', "\\1", $return_data);
And then json_decode that.

Reading REST API Response in PHP

I am trying to read Raven SEO Tools API. It is a REST API and currently it is serving the data backup as an XML (or JSON if I choose) when I just request the URL through a web browser. What is the best method to get the response from their server into my own PHP script for me to then play around with.
Any help much appreciated
Cheers
If you only needs to retrieve a URL and parse its info. The easiest way is curl/JSON combination. Note that parsing JSON is faster than parsing XML.
http://www.php.net/manual/en/function.curl-exec.php
http://www.php.net/manual/en/function.json-decode.php
Something simple as:
$url = "http://api.raventools.com/api?key=B1DFC59CA6EC76FF&method=domains&format=json";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
print_r(json_decode($json));
But if you need to call other methods from this API such as DELETE/PUT, etc. Then to have a REST client in PHP is more elegant solution. A comparison on those clients can be found in PHP REST Clients
I founded this code specifically for Raven API https://github.com/stephenyeargin/raventools-api-php
Sample code:
require 'path/to/raventools-api-php/raventools-api-php.class.php';
$Raven = new RavenTools( 'B1DFC59CA6EC76FF' );
$method = 'domains';
$options = array('format'=> 'json');
$responseString = $Raven->getJSON($method, $options);
print_r(json_decode($responseString));
cUrl
cUrl is a command line tool for getting or sending files using URL syntax.
curl -o example.html www.example.com
file_get_contents
<?php
$homepage = file_get_contents('http://www.example.com/api/parameters');
echo $homepage;
?>
Pecl's HTTPRequest class is a very nice client, I've been using it for a couple of Projects. http://pecl.php.net/package/pecl_http
Another pretty cool client is the Buzz client https://github.com/kriswallsmith/Buzz
It also plays nice with Symfony2 if that's of interest to you :)
You can use either one of them, but I think JSON is the easiest and more hassle-free, unless you use SimpleXML. The decision depends on the complexity of your data.
Given that the JSON returned by the API is valid you can convert it to an array or object by using PHP's json_decode() function.
<?php
# retrieve JSON from API here...
# i.e. it is stored in $data as a string
$object = json_decode($data);
$array = json_decode($data, true);
?>
In SimpleXML, it would be as follows:
<?php
$object = simplexml_load_string($data);
?>

Need help understanding Google Maps API URL?

i am kind of new to API thing, and i need help understanding on what exactly is happening with the below Code.
$address = 'Bhatkal, Karnataka, India';
$requestUrl = 'http://maps.google.com/maps/geo?output=xml&key=aabbcc&oe=utf-8&q='.urlencode($address);
$xml = simplexml_load_file($requestUrl);
i understand that HTTP is capable of sending Request and getting response in return isn't it? what i am unable to understand is the third and last function that is $xml = simplexml_load_file($requestUrl); when i do a print_r($xml) i get an object in return which prints all the object details i got back as response,
how does the function process the
URL?
does it use CURL (i have very less idea about what is CURL).
and where do i look up for Google Maps API URL?
That function does not process the request (nor the URL), only the response, Google processes the URL that, the function just "visit's" it. You can do as well: here. The XML file you see here is ending up in the variable $xml, parsed.
EDIT: the URL in this post is not working too well, because of the key parameter
simplexml_load_file internally uses the fopen wrapper and opens the remote xml that would be produced by the url and then converts into an array for php to easily use.
The response object will help you to extract the data from the response.
Check out the details of Google Maps API

Categories