用 PHP 读取 REST API 响应 [英] Reading REST API Response in PHP

查看:32
本文介绍了用 PHP 读取 REST API 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试阅读 Raven SEO Tools API.它是一个 REST API,目前当我通过 Web 浏览器请求 URL 时,它以 XML(或 JSON,如果我选择)的形式提供数据备份.从他们的服务器获取响应到我自己的 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.

非常感谢任何帮助

干杯

推荐答案

如果您只需要检索 URL 并解析其信息.最简单的方法是 curl/JSON 组合.请注意,解析 JSON 比解析 XML 更快.

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

一些简单的事情:

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

但是如果您需要从该 API 调用其他方法,例如 DELETE/PUT 等,那么在 PHP 中使用 REST 客户端是更优雅的解决方案.可以在 PHP REST 客户端

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

我专门为 Raven API 创建了这段代码 https://github.com/stephenyeargin/raventools-api-php

I founded this code specifically for Raven API https://github.com/stephenyeargin/raventools-api-php

示例代码:

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

这篇关于用 PHP 读取 REST API 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆