2014-12-28 31 views
0

我需要將此「正常」捲曲字符串轉換爲php捲曲。此命令測試,以從殼工作:如何在json中使用curl放入php中?

curl -XPUT http://foo/monitors/1.json -d "Monitor[Name]=test1" 

我已經看過了很多TUTS和例子,但我嘗試到目前爲止都石沉大海。這是我試過的最新消息:

$data = array("Name" => "test1"); 
$payload = json_encode(array("Monitor"=> $data)); 
$url = 'hxxp://foo/monitors/1.json'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$payload); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$response = curl_exec($ch); 
curl_close($ch) 

也是我試圖把對被格式化像這樣JSON:

{"monitor":{"Monitor":{"Id":"1","Name":"test","Type":"Remote","Funct..... 

感謝

*有更多的電流信息更新

+0

請參閱[重複](http://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl)問題。 – kuldipem

+0

對不起,我不確定你的意思? – voldsomenterprise

+0

有一個問題與您的問題相同,可以幫助您解決問題。問題鏈接是[問題](http://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl) – kuldipem

回答

0
$data_string =""/* your json string goes here like {"monitor":{"Monitor":{"Id":"1","Name":"test","Type":"Remote"}} */                    

    $ch = curl_init('http://api.local/rest/users');                  
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                  
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                   
     'Content-Type: application/json',                     
     'Content-Length: ' . strlen($data_string))                  
    );                             

    $result = curl_exec($ch); 
+0

好吧這可能是一種方式,但我試圖導航json開始像這樣︰{「monitor」:{「Monitor」:{「Id」:「1」名稱「:」測試「,」類型「:」遠程.... – voldsomenterprise

+0

謝謝,但我想你誤解了我最初的問題,我只是試圖放棄一個值,而不是整個字符串。 – voldsomenterprise

0

相當於你的命令行示例實在是:

$payload = "Monitor[Name]=test1"; 
$url = 'http://localhost/monitors/1.json'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$payload); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$response = curl_exec($ch); 
curl_close($ch); 

在你的樣品不使用「應用/ JSON」作爲「內容類型」,但實際上股票「應用程序/ x-WWW的形式,進行了urlencoded」的價值和「數據」是不是真的JSON