PHP 使用 curl 提交 json、xml格式raw数据

php之curl 2020-01-16 阅读 134 评论 0

PHP的 curl 类库,使用http方式 post 提交 json、xml 数据,只需要将json、xml等数据,转化成文本,直接放进 curl_setopt($curl, CURLOPT_POSTFIELDS, $data)。PHP 接收这些数据,可以从全局变量 $GLOBALS["HTTP_RAW_POST_DATA"] 获取,使用 json_encode 或者 simplexml_load_string 方法将文本转化为 Array。

post 方法

function post($url, $data, $headers)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $data,
    ));
    if (!empty($headers)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $errno = curl_errno($curl);
    if ($errno) {
        return false;
    }
    curl_close($curl);
    return $response;
}

提交 json 格式数据

提交json数据,可以参考

$arr = [
    "name" => "用户名",
    "password" => "密码",
];
$data = json_encode($arr, JSON_UNESCAPED_SLASHES);
$headers = ["Content-Type: application/json"];
echo post("http://localhost/response.php", $data, $headers);

php 接收post 的json文本数据

$raw = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : null;
$data = json_decode($raw, JSON_OBJECT_AS_ARRAY);
print_r($data);

输出

Array
(
    [name] => 用户名
    [password] => 密码
)

提交xml格式数据

提交 xml 数据,可以参考

$data = <<<EOD
<xml>
<attach>weixin</attach>
<bank_type>ICBC_DEBIT</bank_type>
<cash_fee>2530</cash_fee>
<fee_type>CNY</fee_type>
<is_subscribe>N</is_subscribe>
<return_code>SUCCESS</return_code>
<total_fee>2530</total_fee>
</xml>
EOD;
$headers = ["Content-Type: application/xml"];
echo post("http://localhost/response.php", $data, $headers);

php 接收post的文本,转化为object

$raw = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : null;
$arr = simplexml_load_string($raw, 'SimpleXMLElement', LIBXML_NOCDATA);
print_r($arr);

输出

SimpleXMLElement Object
(
    [attach] => weixin
    [bank_type] => ICBC_DEBIT
    [cash_fee] => 2530
    [fee_type] => CNY
    [is_subscribe] => N
    [return_code] => SUCCESS
    [total_fee] => 2530
)
最后更新 2020-05-14
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });