1

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

谢谢

api 调用接收这些结果

[{"mac":"AC86740410B8","siteId":"1032","name":"main-rtr","desc":"","loc":{"lat":-25.887635,"lng" :28.150488,"levelId":0,"source":"manual"},"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);
4

1 回答 1

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

于 2012-07-20T05:53:20.777 回答