您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 安阳分类信息网,免费分类信息发布

PHP针对Restful返回内容类型的自动识别

2024/5/21 12:17:22发布38次查看
php如何针对restful的返回内容类型进行自动识别?本文主要介绍了php实现自动识别restful的返回内容类型,并实现自动自动渲染成 json、xml等数据格式输出,希望对大家有所帮助。
如题,php如何自动识别第三方restful api的内容,自动渲染成 json、xml、html、serialize、csv、php等数据?
其实这也不难,因为rest api也是基于http协议的,只要我们按照协议走,就能做到自动化识别 api 的内容,方法如下:
1、api服务端要返回明确的 http content-type头信息,如:
content-type: application/json; charset=utf-8 content-type: application/xml; charset=utf-8 content-type: text/html; charset=utf-8
2、php端(客户端)接收到上述头信息后,再酌情自动化处理,参考代码如下:
<?php // 请求初始化 $url = 'http://www.jb51.net'; $ch = curl_init(); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_connecttimeout, 30); // 返回的 http body 内容 $response = curl_exec($ch); // 返回的 http header 的 content-type 的内容 $contenttype = curl_getinfo($ch, 'content_type'); // 关闭请求资源 curl_close($ch); // 结果自动格式输出 $autodetectformats = array( 'application/xml' => 'xml', 'text/xml' => 'xml', 'application/json' => 'json', 'text/json' => 'json', 'text/csv' => 'csv', 'application/csv' => 'csv', 'application/vnd.php.serialized' => 'serialize' ); if (strpos($contenttype, ';')) { list($contenttype) = explode(';', $contenttype); } $contenttype = trim($contenttype); if (array_key_exists($contenttype, $autodetectformats)) { echo '_' . $autodetectformats[$contenttype]($response); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++ // 常用 格式化 方法 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * 格式化xml输出 */ function _xml($string) { return $string ? (array)simplexml_load_string($string, 'simplexmlelement', libxml_nocdata) : array(); } /** * 格式化csv输出 */ function _csv($string) { $data = array(); $rows = explode("\n", trim($string)); $headings = explode(',', array_shift($rows)); foreach( $rows as $row ) { // 利用 substr 去掉 开始 与 结尾 的 " $data_fields = explode('","', trim(substr($row, 1, -1))); if (count($data_fields) === count($headings)) { $data[] = array_combine($headings, $data_fields); } } return $data; } /** * 格式化json输出 */ function _json($string) { return json_decode(trim($string), true); } /** * 反序列化输出 */ function _serialize($string) { return unserialize(trim($string)); } /** * 执行php脚本输出 */ function _php($string) { $string = trim($string); $populated = array(); eval("\$populated = \"$string\";"); return $populated; }
相关推荐:
关于restfulapi使用方法总结
php基于curl扩展制作跨平台的restfule 接口
php编写restful接口的方法
以上就是php针对restful返回内容类型的自动识别的详细内容。
安阳分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录