将wp_remote_post()转换为cURL

时间:2018-11-08 17:24:56

标签: php wordpress curl

我有使用wp_remote_post()的WordPress代码来对LinkedIn进行API调用。

    $args = array(
                'headers' => array('Content-Type' => 'text/xml'),
                'body' => "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><company><id>{$nCompanyID}</id></company>"
            ); 
    $access_token = $datapass->access_token_get();                    
    $params = array('oauth2_access_token' => $access_token); 
    $resource = "https://api.linkedin.com/v1/people/~/following/companies?" . http_build_query($params);        
    $response = wp_remote_post( $resource, $args); 
    $code = $response['response']['code'];
    $body = wp_remote_retrieve_body($response);
    $RV = ($code == '201');
    return $RV;  

有效。现在,我需要将其转换为php cURL。 我尝试了各种在网上找到的PHP cURL发布XML的示例,但是没有运气。 这是最新的尝试。

$access_token = "long_string_of_characters";
$nCompanyID = 2495437;
$xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><company><id>{$nCompanyID}</id></company>";
$url = 'https://api.linkedin.com/v1/people/~/following/companies?oauth2_access_token='.$access_token;

$headers = array(
    "Content-type: text/xml",
    "Content-length: " . strlen($xml)
);

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('body' => $xml));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch); 

$data返回400错误,并显示消息“意外元素:CDATA”。如果我从CURLOPT_POSTFIELDS中删除数组并仅使用$xml,则$ data作为空字符串返回。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果服务器期望XML POST,那么将数组传递给CURLOPT_POSTFIELDS不会令它满意。

在原始代码中注意构建URL的方法:

$params = array('oauth2_access_token' => $access_token); 
$resource = "https://api.linkedin.com/v1/people/~/following/companies?" . http_build_query($params);        

您将要保留它。如果您的访问令牌包含特殊字符,http_build_query()将执行所需的转义。

鉴于原始代码似乎是通过$datapass->access_token_get();动态生成的,因此我会质疑您的访问令牌是否有效

否则,看起来一切设置都相同。

<?php
$access_token = "long_string_of_characters";
$nCompanyID   = 2495437;
$xml          = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><company><id>$nCompanyID</id></company>";
$params       = ["oauth2_access_token" => $access_token]; 
$url          = "https://api.linkedin.com/v1/people/~/following/companies?";
$url         .= http_build_query($params);

$headers = [
    "Content-type: text/xml",
    "Content-length: " . strlen($xml)
];

$ch = curl_init(); 
curl_setopt_array($ch, [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $xml,
    CURLOPT_HTTPHEADER     => $headers,
]);
$data = curl_exec($ch);