2009-10-22 47 views
0

的Ruby代碼:轉換的Ruby代碼爲PHP幫助請

# Turn hash input into JSON, store it in variable called "my_input" 
my_input = { "itemFilter" => { "keywords" => "milk" }}.to_json 
    # Open connection to website.com 
@http = Net::HTTP.new("website.com") 
    # Post the request to our API, with the "findItems" name and our JSON from above as the value 
response_code, data = @http.post("/requests", "findItems=#{my_input}", 
           {'X-CUSTOM-HEADER' => 'MYCUSTOMCODE'}) 
my_hash = Crack::JSON.parse(data) 
my_milk = my_hash["findItems"]["item"].first 

PHP代碼:

$requestBody = json_encode(array("itemFilter" => array("keywords" => "milk"))); 
$headers = array ('X-CUSTOM-HEADER: MYCODE'); 
$connection = curl_init(); 
curl_setopt($connection, CURLOPT_URL, 'website.com/request/findItems='); 
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($connection, CURLOPT_POST, 1); 
curl_setopt($connection, CURLOPT_POSTFIELDS, $requestBody); 
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); 
$response = curl_exec($connection); 
curl_close($connection); 
print_r($response); 
+0

你想要幫忙還是想讓別人爲你寫出整件事? – 2009-10-22 05:21:41

+2

我們會幫助你解決你的問題,但我們不會爲你做你的工作。告訴我們你在這方面付出了一些努力,我們會在剩下的時間幫助你。 – 2009-10-22 05:26:20

回答

0

發現問題..感謝您的輸入。我把一個尾部的斜線放在不需要的地方,json_encode在編碼周圍加上了括號,並且不需要它們。

1

看看json_encodejson_decodecURL擴展。

+0

這是迄今爲止我所擁有的。 $ requestBody = json_encode(array(「itemFilter」=> array(「keywords」=>「milk」))); $ headers = array('X-CUSTOM-HEADER:MYCODE'); $ connection = curl_init(); curl_setopt($ connection,CURLOPT_URL,'http://www.website.com/request/findItems='); curl_setopt($ connection,CURLOPT_HTTPHEADER,$ headers); curl_setopt($ connection,CURLOPT_POST,1); curl_setopt($ connection,CURLOPT_POSTFIELDS,$ requestBody); curl_setopt($ connection,CURLOPT_RETURNTRANSFER,1); $ response = curl_exec($ connection); curl_close($ connection); print_r($ connect – Brad 2009-10-22 07:02:03

+0

它不工作..我猜我要去的URL或POST字段錯誤,因爲它看到我的自定義標題代碼就好了。 – Brad 2009-10-22 07:03:32

+0

編輯你的問題;添加你的代碼,預期的結果和實際結果,用4個空格縮進每行代碼,將其格式化爲代碼。 – outis 2009-10-22 07:39:47