使用cURL读取JSON数据

时间:2013-07-27 06:20:33

标签: php json curl

使用Chrome检查网址:http://www.wizards.com/Magic/PlaneswalkerPoints/76954206#我能够看到抓取JSON数据的网址:

请求网址:http://www.wizards.com/Magic/PlaneswalkerPoints/JavaScript/GetPointsSummary/76954206

运行我的代码:

$user_agent = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36'; 
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // times out after 5s
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($json)));
curl_setopt($ch, CURLOPT_POST, 1);

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { 
  print_r($ch);
} else {
  echo "Boo";
}

给我留个空白页面。它没有返回JSON,只返回重定向错误页面。

我是否缺少一个可以获取JSON数据的电话?

1 个答案:

答案 0 :(得分:2)

试试这个:

<?php

$url = 'http://www.wizards.com/Magic/PlaneswalkerPoints/JavaScript/GetPointsSummary/76954206';

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS, '');
$result = curl_exec($ch);
curl_close($ch);

echo $result;

输出:

  

{ “结果”:真 “sessionExpired时”:假, “数据”:[{ “密钥”: “LifetimePoints”, “值”:6016,“ReplaceElement ...