2016-09-06 42 views
0

我有以下代碼在命令行中正常工作。現在在PHP中更改捲曲

curl -F customerid=1 -F username=admin -F password=admin -F deviceid=ID5500 -F [email protected]/var/www/html/test/sample.xml http://192.168.100.27:8080/trafficinsight/api/v1/setdataxml 

,我想改變它的PHP代碼,我的代碼如下:

<?php 
     $fields = array 
     (
      'customerid' =>1, 
      'username'   =>'admin', 
      'password'   =>'admin', 
      'deviceid'   =>'ID5500', 
      'values'   =>'@/var/www/html/test/sample.xml', 
      'start'   =>'2016-05-24T16:00', 
      'end'   =>'2016-05-24T17:00' 
     ); 
     $ch = curl_init(); 
     curl_setopt($ch,CURLOPT_URL, 'http://192.168.100.27:8080/trafficinsight/api/v1/setdataxml'); 
     curl_setopt($ch,CURLOPT_POST, true); 
     curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields)); 
     $result = curl_exec($ch); 
     curl_close($ch); 

    echo '<pre>'; print_r($result); 


    die; 


?> 

我的XML數據是:

<data> 
<datum time="2016-09-02T16:00" c1="1" c2="1" c3="1" c4="1"/> 
<datum time="2016-09-02T17:00" c1="21" c2="1" c4="1"/> 
<datum time="2016-09-02T18:00" c2="27"/> 
<datum time="2016-09-02T16:00" c1="12" c2="21" c3="21" c4="7"/> 
<datum time="2016-09-02T19:00" c1="29"/> 
</data> 

但它現在的工作,我得到錯誤。

[響應] => ERROR [responseCode] => 400

+0

是否有可能請求的接收方期待post字段爲json,或者其中一個字段應該是不同的格式? –

回答

2

不要使用http_build_query(),只要給該陣列作爲CURLOPT_POSTFIELDS陣列。文件上傳不能放入URL編碼的字符串中。

curl_setopt($ch,CURLOPT_POSTFIELDS, $fields); 

此外,在後場利用@在PHP 5.5中棄用。如果您使用的是5.5.0或更高版本,則應該使用CURLFile類。

$fields = array 
    (
     'customerid' =>1, 
     'username'  =>'admin', 
     'password'  =>'admin', 
     'deviceid'  =>'ID5500', 
     'values'  => new CURLFile('/var/www/html/test/sample.xml', 'text/xml', 'sample.xml'), 
     'start'   =>'2016-05-24T16:00', 
     'end'   =>'2016-05-24T17:00' 
    );