Reading REST API Response in PHP

2020-07-20 04:07发布

问题:

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

回答1:

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.

  1. http://www.php.net/manual/en/function.curl-exec.php
  2. 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));


回答2:

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;
?>


回答3:

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 :)



回答4:

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);

?>


标签: php xml api rest