使用 Curl 以 XML 格式发布数据

Posting data using Curl in XML Format

目前 post 我的数据采用 HTTP Post 格式,我需要 post 它在 XML 中并添加 header.

这就是我目前 post 我的数据。

//extract data from the post
extract($_POST);

//set POST variables
$url = 'https://test.com/checklead';
$fields = array(
                        'surname' => urlencode($surname),
                        'first_name' => urlencode($first_name),
                        'dob' => urlencode($dob),
                        'email' => urlencode($email),
                        'home_phone' => urlencode($home_phone),
                        'mobile_phone' => urlencode($mobile_phone),
                        'work_phone' => urlencode($work_phone),
                        'postcode' => urlencode($postcode),
                        'leadid' => urlencode(123),
                        'affid' => urlencode(123),
                        'subid' => urlencode(123),
                        'bank_acno' => urlencode($bank_acno),
                        'bank_sort' => urlencode($bank_sort),
                        'amount_required' => urlencode($amount_required),

                );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

我如何 post 在 XML 格式中添加一个 Header : http://www.header.com

您还没有设置内容类型。 尝试以下方式:

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Header1: my_header_value'
    ));
$output = curl_exec($ch);

或者您可以考虑使用诸如 Guzzle 之类的库,它可以为您处理很多错误等。