PHP xml接口对接相关


下面介绍下PHP中关于xml接口对接相关的内容


正文

有时会碰到对接xml接口的场景,提交的参数是xml格式内容,返回的也是xml格式内容。

下面代码:

class Curl
{
    public static function post($url, $poststr = '')
    {
        //初始化
        $ch = curl_init();

        //设置选项,包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $poststr);

        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
}

// 准备xml内容
$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<Packet type="REQUEST" version="1.0">';
...
$xml .= '</Packet>';

$url = '接口RUL地址';

// 接口请求
$res_api = Curl::post($url, $xml);

// 接口返回结果处理
// 禁止引用外部xml实体
libxml_disable_entity_loader(true);
// 先把xml转换为simplexml对象,再把simplexml对象转换成 json,再将 json 转换成数组。
$res_array = json_decode(json_encode(simplexml_load_string($res_api, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

// 业务逻辑
...

$res_array是对应的xml的array表示。

操作两次就知道具体怎么回事了。

函数原型

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Interprets a string of XML into an object

说明

simplexml_load_string ( string $data , string $class_name = "SimpleXMLElement" , int $options = 0 , string $ns = "" , bool $is_prefix = false ) : SimpleXMLElement|false

Takes a well-formed XML string and returns it as an object.

参数

data

A well-formed XML string

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

true if ns is a prefix, false if it's a URI; defaults to false.

返回值

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, 或者在失败时返回 false.

警告 此函数可能返回布尔值 false,但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

错误/异常

Produces an E_WARNING error message for each error found in the XML data.

小技巧 Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.






参考资料

PHP 手册 函数参考 XML 操作 SimpleXML SimpleXML 函数 simplexml_load_string https://www.php.net/simplexml_load_string

PHP simplexml_load_string() 函数 https://www.runoob.com/php/func-simplexml-load-string.html


返回