通过curl调用API,json导致csv或mysql

时间:2012-07-20 05:50:28

标签: php json curl

我是PHP新手,我需要通过curl调用api并将结果解析为我可以导入数据库的格式。如何将结果保存为csv或将其直接推送到数据库?

由于

api呼叫接收这些结果

[{ “MAC”: “AC86740410B8”, “网站ID”: “1032”, “名称”: “主RTR”, “降序”: “”, “LOC”:{ “LAT”: - 25.887635, “LNG”:28.150488, “levelId”:0, “源”: “手动”}, “lrrt”:1, “lrne”:4}]

这是我的代码

$ch = curl_init();
$fp = fopen("data.txt", "a+");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://theapi.com/');
curl_setopt ($ch, CURLOPT_USERPWD, "username:password");
curl_setopt ($ch, CURLOPT_FILE, $fp);
CURLOPT_HTTPHEADER >= array('Content-type: application/json');
$json = ('data.txt');
//json_decode($json, true);
//$data = json_decode(file_get_contents('data.txt'), true);
var_dump(json_decode($json));
var_dump(json_decode($json, true));
curl_exec($ch);
curl_close($ch);
fclose($fp);

1 个答案:

答案 0 :(得分:0)

您可以像这样访问解码结果:

$data = json_decode('[{"mac":"AC86740410B8","siteId":"1032","name":"main-rtr","desc":"","loc":{"lat":-25.887635,"lng":28.150488,"levelId":0,"source":"manual"},"lrrt":1,"lrne":4}]');

$arrayFromResults = array(
  $data[0]->mac,
  $data[0]->loc->lat,
  $data[0]->lrne
);

var_dump( $arrayFromResults ); 

var_dump( $data ); 

http://codepad.org/kzZ7nhck

然后轻松将数组传递给putcsv:

http://php.net/manual/en/function.fputcsv.php

...或将其写入数据库:

http://www.php.net/manual/de/pdo.exec.php