api接口对接如何实现,php如何对接api

news2024/10/5 14:03:04

这篇文章来分享下api接口对接如何实现,还有源码,希望对新手有所帮助。

什么是API?

我的回答:API( 应用程序编程接口):一般来说,这是一套明确定义的各种软件组件之间的通信方法。

什么是API?我们不妨用一个小故事展示出来:

研发人员A开发了软件A,研发人员B正在研发软件B。

有一天,研发人员B想要调用软件A的部分功能来用,但是他又不想从头看一遍软件A的源码和功能实现过程,怎么办呢?

研发人员A想了一个好主意:我把软件A里你需要的功能打包好,写成一个函数;你按照我说的流程,把这个函数放在软件B里,就能直接用我的功能了!

其中,API就是研发人员A说的那个函数。

进一步解释:

比如c语言的fopen()函数来打开一个文件,感觉非常简单。

但是操作到底层是非常复杂的,打开文件需要扫描硬盘,找到我文件位置,然后读取部分数据,并放进i/o缓存中,放进内存。

这些数据都是0,1序列,还要对照ASCII表或者unicode表翻译成字符,再在显示器上显示出来。如果这个过程让程序员来完成,简直就是个噩梦。不可能的事。

怎么办呢?

操作系统就想了一个很好的办法。它预先把复杂的操作写在一个函数里面,编译成一个组件(一般是动态链接库)程序员只需要简单的调用这些函数就可以用完成复杂的工作。

这些封装好的函数就叫做API。

<?php


set_time_limit(270);
error_reporting(E_ERROR | E_WARNING | E_PARSE);

define('TITLE_SEPAR', 'xxx**xxx');
define('TITLE_SEPAR2', '262661');


$url = 'http://api-9.xiaofamao.com/api.php?json=0&v=1&key=tttttt';

$content_tag_name = '内容';

$headdd = '';
$taill = '';

switch($LabelArray['PageType'])
{
    case 'Save'://只有保存时是可以处理标签值的
        // 保存原文

    try {
    $title = $LabelArray['标题'];
    $title = '标题:'.$title;

    $content = $LabelArray[$content_tag_name];
    #$content = str_replace('2020/', '2020_', $content);

    $article_src = compose_article($title, $content);
    $article_src_b = $article_src;

    $article_new = get_wyc_article($article_src);


    $title_wyc = trim($article_new[0]);
    $content_wyc = trim($article_new[1]);

    $content_wyc = fix_newline($content_wyc);
    $content_wyc = str_replace('标签:', '标签:', $content_wyc);
    $LabelArray[$content_tag_name] = $headdd. $content_wyc. $taill;

    $title_wyc = str_replace(array('。',',','%'), array(' ',' ',' '), $title_wyc);
    $LabelArray['标题'] = $title_wyc;
    }
    catch (Exception $e) {
        $LabelArray['标题'] .= $e->getMessage();
        $LabelArray[$content_tag_name] .= $e->getMessage();
    }
        break;
    default:
}

echo serialize($LabelArray);



function compose_article($title, $content) {
    $separator = compose_separator();
    return $title.$separator.$content;
}

function compose_separator() {
    return PHP_EOL.'('.TITLE_SEPAR2.')'.PHP_EOL;
}


function fix_separator($article) {
    return $article;
}


function get_wyc_article($str) {
    global $url;
    $separator = compose_separator();
    $separator = str_replace(PHP_EOL, '', $separator);
    $wyc = curl_request($url, array('wenzhang'=>$str));

    $wyc_f = $wyc;
    $wyc = fix_separator($wyc);
    $wyc = explode($separator, $wyc);

    if (isset($wyc[0])){
        $wyc[0] = str_replace('标题:', '', $wyc[0]);
        $wyc[0] = str_replace('标题:', '', $wyc[0]);
        $wyc[0] = str_replace('目:', '', $wyc[0]);
        $wyc[0] = str_replace('目:', '', $wyc[0]);
        $wyc[0] = 'xx`xx'.$wyc[0];
        $wyc[0] = str_replace('xx`xx题', '', $wyc[0]);
        $wyc[0] = str_replace('xx`xx', '', $wyc[0]);
    }

    return $wyc;
}


function get_wyc_title($str) {
    $title = get_wyc_article($str.PHP_EOL.PHP_EOL.PHP_EOL.$str.PHP_EOL.PHP_EOL.PHP_EOL.$str);
    $title = fix_newline($title);
    $title = explode(PHP_EOL, $title);
    return $title[0];
}

function get_keywords($title, $contents) {
    $url_kw = 'http://api-2.78tp.com/nlp/kws.php?appid=';
    $kws = curl_request($url_kw, array(
    'title'=>$title,
    'len'=>100,
    'text'=>$contents));

    return $kws;
}


function remove_alt($contents) {
    $contents = preg_replace('/alt=\"(.*)\"/', '', $contents);
    return $contents;
}


function fix_title($contents) {
    $punctuation_symbol = array('。', '?', ',', ':', ';', '、', '!',
                                '.',  '?',  ',',  ':',  ';', '!');

     $contents = str_replace($punctuation_symbol, '', $contents);
    return $contents;
}

function br2newline($contents) {
    $contents = str_replace('<br>', PHP_EOL, $contents);
    $contents = str_replace('<br/>', PHP_EOL, $contents);
    $contents = str_replace('<br />', PHP_EOL, $contents);
    $contents = str_replace('<BR/>', PHP_EOL, $contents);
    $contents = str_replace('<BR>', PHP_EOL, $contents);
    $contents = str_replace('<BR />', PHP_EOL, $contents);

    return $contents;
}

function newline2br($contnets) {
    $contnets = str_replace(PHP_EOL, "<br>", $contnets);
    $contnets = str_replace('<p><br>', '<p>', $contnets);
    return $contnets;
}


function delete_newline($contents) {
    $contents = fix_newline($contents);
    return $contents;
}

function reset_newline_win($contents) {
    // 优化换行符
    $contents = str_replace("\r\n", "\n", $contents);
    $contents = str_replace("\r", "\n", $contents);
    $contents = str_replace("\n", PHP_EOL, $contents);

    return $contents;
}

function fix_newline($data) {
    $data = str_replace("\r", "\n", $data);
    while(strpos($data, "\n\n") !== false) {
        $data = str_replace("\n\n", "\n", $data);
    }
    $data = str_replace("\n", PHP_EOL, $data);

    return $data;
}

function clean_contents($contents) {
    $sa = new cleanHtml;  
    $sa->allow = array( 'src' );    
    $sa->exceptions = array(  
    'img' => array( 'src', 'alt' ),  
    //'a' => array( 'href', 'title' ),  
    'iframe'=>array('src','frameborder'),  
    ); 
    $str = $sa->strip( $contents );   

    return $str;
}


function xfm_strong_str_replace_once($search, $replace, $subject) {
    $firstChar = strpos($subject, $search);
    if($firstChar !== false) {
        $beforeStr = substr($subject,0,$firstChar);
        $afterStr = substr($subject, $firstChar + strlen($search));
        return $beforeStr.$replace.$afterStr;
    } else {
        return $subject;
    }
}

//参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
function curl_request($url,$post='',$cookie='', $returnCookie=0){
    if (! extension_loaded('curl')) {
        file_exists('./ext/php_curl.dll') && dl('php_curl.dll'); // 加载扩展
    }
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    if (ini_get('open_basedir') == '' && strtolower(ini_get('safe_mode')) != 'on'){ 
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    }
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 150);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            return $data;
        }
}

//echo $tag;
// 计算中文字符串长度
function utf8_strlen($string = null) {
// 将字符串分解为单元
preg_match_all("/./us", $string, $match);
// 返回单元个数
return count($match[0]);
}


function reg_escape( $str )  
{  
    $conversions = array( "^" => "\^", "[" => "\[", "." => "\.", "$" => "\$", "{" => "\{", "*" => "\*", "(" => "\(", "\\" => "\\\\", "/" => "\/", "+" => "\+", ")" => "\)", "|" => "\|", "?" => "\?", "<" => "\<", ">" => "\>" );  
    return strtr( $str, $conversions );  
}  
  
/** 
* Strip attribute Class 
* Remove attributes from XML elements 
* @author David (semlabs.co.uk) 
* @version 0.2.1 
*/  
  
class cleanHtml{  
      
    public $str         = '';  
    public $allow       = array();  
    public $exceptions  = array();  
    public $ignore      = array();  
      
    public function strip( $str )  
    {  
        $this->str = $str;  
          
        if( is_string( $str ) && strlen( $str ) > 0 )  
        {  
            $res = $this->findElements();  
            if( is_string( $res ) )  
                return $res;  
            $nodes = $this->findAttributes( $res );  
            $this->removeAttributes( $nodes );  
        }  
          
        return $this->str;  
    }  
      
    private function findElements()  
    {  
        # Create an array of elements with attributes  
        $nodes = array();  
        preg_match_all( "/<([^ !\/\>\n]+)([^>]*)>/i", $this->str, $elements );  
        foreach( $elements[1] as $el_key => $element )  
        {  
            if( $elements[2][$el_key] )  
            {  
                $literal = $elements[0][$el_key];  
                $element_name = $elements[1][$el_key];  
                $attributes = $elements[2][$el_key];  
                if( is_array( $this->ignore ) && !in_array( $element_name, $this->ignore ) )  
                    $nodes[] = array( 'literal' => $literal, 'name' => $element_name, 'attributes' => $attributes );  
            }  
        }  
          
        # Return the XML if there were no attributes to remove  
        if( !$nodes[0] )  
            return $this->str;  
        else  
            return $nodes;  
    }  
      
    private function findAttributes( $nodes )  
    {  
          
        # Extract attributes  
        foreach( $nodes as &$node )  
        {  
            preg_match_all( "/([^ =]+)\s*=\s*[\"|']{0,1}([^\"']*)[\"|']{0,1}/i", $node['attributes'], $attributes );  
            if( $attributes[1] )  
            {  
                foreach( $attributes[1] as $att_key => $att )  
                {  
                    $literal = $attributes[0][$att_key];  
                    $attribute_name = $attributes[1][$att_key];  
                    $value = $attributes[2][$att_key];  
                    $atts[] = array( 'literal' => $literal, 'name' => $attribute_name, 'value' => $value );  
                }  
            }  
            else  
                $node['attributes'] = null;  
              
            $node['attributes'] = $atts;  
            unset( $atts );  
        }  
          
        return $nodes;  
    }  
      
    private function removeAttributes( $nodes )  
    {  
          
        # Remove unwanted attributes  
        foreach( $nodes as $node )  
        {  
              
            # Check if node has any attributes to be kept  
            $node_name = $node['name'];  
            $new_attributes = '';  
            if( is_array( $node['attributes'] ) )  
            {  
                foreach( $node['attributes'] as $attribute )  
                {  
                    if( ( is_array( $this->allow ) && in_array( $attribute['name'], $this->allow ) ) || $this->isException( $node_name, $attribute['name'], $this->exceptions ) )  
                        $new_attributes = $this->createAttributes( $new_attributes, $attribute['name'], $attribute['value'] );  
                }  
            }  
            $replacement = ( $new_attributes ) ? "<$node_name $new_attributes>" : "<$node_name>";  
            $this->str = preg_replace( '/'. reg_escape( $node['literal'] ) .'/', $replacement, $this->str );  
        }  
          
    }  
      
    private function isException( $element_name, $attribute_name, $exceptions )  
    {  
        if( array_key_exists($element_name, $this->exceptions) )  
        {  
            if( in_array( $attribute_name, $this->exceptions[$element_name] ) )  
                return true;  
        }  
          
        return false;  
    }  
      
    private function createAttributes( $new_attributes, $name, $value )  
    {  
        if( $new_attributes )  
            $new_attributes .= " ";  
        $new_attributes .= "$name=\"$value\"";  
          
        return $new_attributes;  
    }  
  
}  

?>

参考:如何对接伪原创API 更加通俗讲:别人写好的代码,或者编译好的程序,提供给你使用,就叫做api。

因为你使用了别人的代码( 或者程序)中的某个函数,类,对象,就叫做使用了某个api。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/173710.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android数据库之SharedPreferences、SQLite、Room

文章目录一、SharedPreferences二、SQLite三、Room使用Room进行增删改查Room数据库升级一、SharedPreferences 要想使用SharePreferences来存储数据&#xff0c;首先需要获取到SharedPreferences对象。Android中提供了三种方法用于得到SharedPreferences对象 1.Context类中的g…

20230119英语学习

Back to the Future 在故宫修钟表是种什么样的体验&#xff1f; After a year of complex restoration, specialists from the Palace Museum in Beijing have given a pair of antique pagoda clock automata a new lease on life. In the form of a nine-tiered pagoda, th…

单片机寄存器

单片机寄存器简述 1、单片机寄存器就是单片机片内存储器&#xff08;片内RAM)一部分&#xff0c;每一个都有地址。只不过这几个寄存器有特殊的作用&#xff0c;比如指令&#xff1a;MUL AB,这条指令用到两个寄存器A,B进行乘法&#xff0c;结果存到BA里面&#xff0c;这条指令必…

Linux基本功系列之type命令实战

文章目录一. type命令介绍二. 语法格式及常用选项三. 参考案例3.1 查看别名3.2 查看是否是内建命令3.3 查看是否为关键字3.4 显示所有命令的位置3.5 判断当前命令是否为alias或者keyword等总结前言&#x1f680;&#x1f680;&#x1f680; 想要学好Linux&#xff0c;命令是基本…

4-2指令系统-指令的寻址方式

文章目录一.指令寻址1.顺序寻址2.跳跃寻址二.数据寻址1.隐含寻址2.立即&#xff08;数&#xff09;寻址3.直接寻址4.间接寻址5.寄存器寻址6.寄存器间接寻址7.相对寻址&#xff08;程序浮动、转移指令&#xff09;8.基址寻址&#xff08;多道程序&#xff09;9.变址寻址&#xf…

移动web字体图标

字体图标下载字体图标使用字体图标使用类名引入字体图标使用unicode编码(了解)在线字体图标使用伪元素字体图标小结下载字体图标 具体的步骤&#xff1a; 使用字体图标 引入相关文件 复制相关的文件&#xff0c;到 fonts文件夹里面。 引入 css <link rel"styleshe…

回溯法复习(总结篇)

根据课本上的学习要点梳理&#xff0c;“通用解题法”&#xff0c;可以系统的搜索一个问题的所有解、任一解&#xff0c;他是一个既带有系统性&#xff08;暴力遍历&#xff09;又带有跳跃性&#xff08;剪枝&#xff09;的搜索算法。 理解回溯法和深度优先搜索策略 回溯的本质…

Kafka入门与核心概念

前言在我们开发过程中&#xff0c;有一些业务功能比较耗时&#xff0c;但是又不是很重要的核心功能&#xff0c;最典型的场景就是注册用户以后发送激活邮件分为两步1&#xff1a;向数据库插入一条数据2&#xff1a;向注册用户发送邮件第2步其实并不是核心功能&#xff0c;但是发…

SpringMVC-拦截器

1&#xff0c;pringMVC-拦截器 对于拦截器这节的知识&#xff0c;我们需要学习如下内容: 拦截器概念入门案例拦截器参数拦截器工作流程分析 1.1 拦截器概念 讲解拦截器的概念之前&#xff0c;我们先看一张图: (1)浏览器发送一个请求会先到Tomcat的web服务器 (2)Tomcat服务…

字节青训前端笔记 | 响应式系统与 React

本节课为前端框架 React 的基础课程讲解 React的设计思路 UI编程的特点 状态更新的时候&#xff0c;UI不会自动更新&#xff0c;需要手动调用DOM接口进行更新欠缺基本的代码层面的封装和隔离&#xff0c;代码层面没有组件化UI之间的数据依赖关系&#xff0c;需要手动维护&am…

【程序人生 | 价值扳机】你的寒假自律第一步(建议收藏)

&#x1f482;作者简介&#xff1a; THUNDER王&#xff0c;一名热爱财税和SAP ABAP编程以及热爱分享的博主。目前于江西师范大学会计专业大二本科在读&#xff0c;阿里云社区专家博主&#xff0c;华为云社区云享专家&#xff0c;CSDN SAP应用技术领域新兴创作者。   在学习工…

小技巧:Excel顽固的名称、引用冲突的解决

共享编辑、跨文档引用的不便 Excel 的共享文档多人编辑、跨文档引用等功能似乎很美好&#xff0c;实际用下来很成问题。 首先共享文档虽然用约定按标注责任人的方式由不同的人编辑不同的行避免的多人同时编辑一行的冲突&#xff0c;但是这通常是个大文件&#xff0c;经常(大概…

函数 C语言】

函数的声明和定义 函数间调用关系是&#xff0c;由于函数调用其他函数&#xff0c;替他函数也可以互相调用&#xff0c;同一个函数可以被一个或多个函数调用任意次。 先声明&#xff0c;后调用。 #include <stdio.h> //去标准库下找文件 #include "stdio.h"…

分件操作和IO

1.文件的路径如图:当我们打开此电脑后(windows系统),上面会显示我们当前的位置&#xff0c;点击之后会出现如图片中的一段字符&#xff0c;这段字符代表着当前你所处位置的路径。最开头的D&#xff1a;/d&#xff1a;是盘符&#xff0c;后面会用斜杠‘/’或者反斜杠‘\’分开,该…

MFC的使用

1.初使用的简单代码该程序包含两个代码 头文件mfc.h和mfc.cpp文件头文件mfc.h#pragma once #include<afxwin.h>class MyApp:public CWinApp//CWinApp应用程序类 { public://程序入口virtual BOOL InitInstance(); }; class MyFrame : public CFrameWnd//继承窗口框架类a …

Java_Git:2. 使用git管理文件版本

目录 1 创建版本库 1.1 使用GitBash 1.2 使用TortoiseGit 2 添加文件 2.1 添加文件过程 2.2 工作区和暂存区 3 修改文件 3.1 提交修改 3.2 查看修改历史 3.3 差异比较 3.4 还原修改 4 删除文件 5 案例&#xff1a;将java工程提交到版本库 5.1 复制文件到工作目录 …

论文阅读:Boosting 3D Object Detection by Simulating Multimodality on Point Clouds

Boosting 3D Object Detection by Simulating Multimodality on Point CloudsResponse DistillationSparse-Voxel DistillationVoxel-to-Point DistillationInstance DistillationlossExperiments稠密&#xff08;多模态、多帧&#xff09;信息->稀疏&#xff08;单模态点云…

【华为上机真题 2023】数组去重和排序 (华为机考真题)

&#x1f388; 作者&#xff1a;Linux猿 &#x1f388; 简介&#xff1a;CSDN博客专家&#x1f3c6;&#xff0c;华为云享专家&#x1f3c6;&#xff0c;Linux、C/C、云计算、物联网、面试、刷题、算法尽管咨询我&#xff0c;关注我&#xff0c;有问题私聊&#xff01; &…

2023/1/20 ES6基本语法学习

1 let 命令的解读 1 let 声明变量&#xff0c;没有变量提升 <script>// 不存在变量提升console.log(variable)let variable zhaoshuai-lc </script>2 作用域 全局作用域函数作用域&#xff1a;function() {}块级作用域&#xff1a;{} let 是一个块作用域 <…

Spring中涉及的设计模式总结

Spring中涉及的设计模式总结 1.简单工厂(非23种设计模式中的一种) 实例化阶段主要是通过反射或者CGLIB对bean进行实例化&#xff0c;在这个阶段Spring又给我们暴露了很多的扩展点&#xff1a; 实现方式&#xff1a;BeanFactory。Spring中的BeanFactory就是简单工厂模式的体现…