2016-09-06 115 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' 
    );