2013-02-14 53 views
0

我想在本地服務器上發佈PHP中的一些JSON數據。我在下面的代碼,但它不起作用。我錯過了一件重要的事情嗎?發佈使用PHP的JSON Curl

$url = 'http://localhost/mmcv/chart1.php'; 

    //open connection 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL,$url);   
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                  
    curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json')); 


    $result = curl_exec($ch); 
+0

您是否首先在服務器中啓用curl? – 2013-02-14 14:15:28

+0

如果(!function_exists('curl_init'))拋出新的異常('PHP cURL擴展不存在'),請檢查curl是否已啓用或未在您的服務器中使用此代碼。 } – 2013-02-14 14:17:34

+0

@Venkat我不太確定,如果我有。我以前使用curl從API獲取數據,這是否意味着我必須在我的末端啓用它? – AndroidEnthusiast 2013-02-14 14:18:39

回答

1

也許你的問題在接收腳本中。 請在「mmcv/chart1.php」中嘗試以下操作:

$rawInput = file_get_contents('php://input'); 

if(is_string($rawInput)) { 
    if(!is_null($jsonInput = json_decode($rawInput, true))) 
     $_POST = $jsonInput; 
} 
+0

謝謝這絕對有幫助!這是我的代碼中的一行問題 – AndroidEnthusiast 2013-02-14 15:06:46

1
curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json')); 

即使你張貼JSON你還是要在URL編碼的形式發送數據,以便把它像

curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/x-www-form-urlencoded')); 

,並使用

curl_setopt($ch, CURLOPT_POST, TRUE); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

代替

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);