2013-05-13 57 views
0

我試圖創建一個PHP腳本,它將一些JSON數據和壓縮文件一起發送到一個API(InMobi),但我無法讓它工作。我通常只需將頭文件設置爲application/json並使用curl_setopt($ ch,CURLOPT_POSTFIELDS,json_encode($ data));其中$ data是一個PHP數組,但是如何將文件附加到該數組上?如何製作發送JSON數據和二進制文件的cURL文章?

請求應該是這樣的:

Content-Type: multipart/form-data; boundary=AYip2bnLbOw0R2vf8lDZ71pon3CDottfPlckt-E Content-Disposition: form-data; name="payload" 
Content-Type: application/json; charset=US-ASCII 
Content-Transfer-Encoding: 8bit 
{ 
    "campaign": { 
     "name": "campaign-with-banner-ad", 
     "dailyBudget": "2000.00", 
     "startDate": "2012-03-10", 
     "endDate": "2012-05-31", 
     "action": "create", 
     "adGroups": [ 
      { 
       "countryId": 94, 
       "name": "First AdGroup", 
       "bid": "1.89", 
       "landingURL": "http://test.inmobi.com/sampleapp", 
       "ctaDetails": { 
        "id": "1" 
       }, 
       "action": "create", 
       "ads": [ 
        { 
         "type": "banner", 
         "name": "From Root", 
         "filePath": "/", 
         "altText": "3 img add", 
         "action": "create" 
        }, 
        { 
         "type": "banner", 
         "name": "From ad1", 
         "filePath": "/ad1/", 
         "action": "create" 
        }, 
        { 
         "type": "banner", 
         "name": "From ad2", 
         "filePath": "/ad2/", 
         "action": "create" 
        } 
       ] 
      } 
     ] 
    } 
} 
--AYip2bnLbOw0R2vf8lDZ71pon3CDottfPlckt-E 
Content-Disposition: form-data; name="zipFile"; filename="banners.zip" Content-Type: application/octet-stream; charset=ISO-8859-1 
Content-Transfer-Encoding: binary 

<Contents of ZIP File> 

在所有我見過他們將文件放在CURLOPT_POSTFIELDS的例子,但我不知道如何在結合了json_encode和上述要求長相就像文件在請求的一個單獨部分發送一樣。

謝謝!

回答

3

分割數據分成兩個字段:

$postdata = array(
    'json' => json_encode($whatever), 
    'zipfile' => '@/path/to/yourfile.zip' 
); 

curl_setopt($curl, CURLOPT_POST_FIELDS, $postdata); 

然後在接收端:

$json = json_decode($_POST['json'); 
$file = $_FILES['zipfile'];