使用post请求将JSON结果获取到PHP数组中

时间:2014-01-26 21:47:12

标签: php json curl

嗨我的代码有问题。

我使用curl登录网站。然后我转到sub并发送POST请求以获得JSON格式的结果。不幸的是,结果我得到:NULL

// options
$EMAIL            = '...';
$PASSWORD         = '...';
$cookie_file_path = "cookies/cookies.txt";
$LOGINURL         = "https://www.domainname.com/auth/login"; 
$agent            = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36";


$ch = curl_init(); 

$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-Type: application/json";


curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers);
curl_setopt($ch, CURLOPT_HEADER,  0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);         
curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 



$fields = array(); 
$fields['username'] = $EMAIL;
$fields['password'] = $PASSWORD;



$POSTFIELDS = http_build_query($fields); 

curl_setopt($ch, CURLOPT_URL, $LOGINURL); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS); 

$result = curl_exec($ch);  


    $params = array(
    'akcja' =>'test1',
    'Bank' =>'null',
    'Produkt' =>'test2',
    'ProwKOd' =>'undefined',
    'domainKey'=>'326',
 );
    $remotePageUrl = 'http://www.domainname.com/users/Links';
    curl_setopt($ch,CURLOPT_POST,count($params));
    curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_URL, $remotePageUrl); 
    $result = curl_exec($ch);  

  curl_close($ch);



print var_dump(json_decode($result,true));

我尝试以json格式发送数据,但遗憾的是没有帮助。

修改

应该显示脚本的一段数据。

{"tabela":"\r\n\t\t\t\t<div class='provisionBox'>\r\n\t\t\t\t    <img src = '\/img\/promotedIcon.png' class='promotionSign' \/>\r\n\t\t\t\t    <div class='provisionBoxLeft'>\r\n\t\t\t\t    \t<div class='provBoxRodzajIcon'> <img class='' src='\/_img\/product_icon\/konto_osobiste.png' alt='Konto osobiste' \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle='Konto osobiste'><\/div>\r\n\t\t\t\t\t\t<div class='provBoxProductKind'>Rachunek osobisty \"Konto osobiste PLN\"<\/div>\r\n\t\t\t\t\t\t<div class='clear'><\/div>\r\n\t\t\t\t    \t<div class='provBoxBankLogo'>

2 个答案:

答案 0 :(得分:0)

您在请求标头上使用Content-Type: application/json。所以你的Post数据应该是json格式。将这个用于POST参数。

curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($params));

答案 1 :(得分:0)

问题解决了:) !!!! 我修改了请求标题。 有效值:

$headers[] = "Accept: application/json, text/javascript, */*; q=0.01";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "X-Requested-With:XMLHttpRequest";

非常感谢你的帮助!