LoginSignup
10
9

More than 5 years have passed since last update.

PHPでXMLを返却するAPIのレスポンスを受け取りそのままCSVとしてダウンロードさせちゃう

Last updated at Posted at 2014-06-19

久々にphp書いたので晒します。
「今どきxmlとかこれ何のAPIだよwww」というツッコミは受け付けません、察してください。

// 初期設定
$API_ID = 'YOUR API ACCESS ID';
$API_PASSWORD = 'YOUR API ACCESS PASSWORD';
$API_VERSION = '1.0';
$API_ENDPOINT_URI = 'http://foo.var/api';

$data = array(
  "api_id"        => $API_ID,
  "api_pass_hash" => md5($API_PASSWORD . time()),
  "version"       => $API_VERSION,
  "condition"     => 'paid'
);

// postで接続
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_ENDPOINT_URI);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

// xmlをパース
$xml = simplexml_load_string($response);
$data = get_object_vars($xml);

// ファイル名
$filename = "getdata" . date('Ymd-His') . ".csv";
$f = fopen('php://output', 'w');

// バッファに読み込む
ob_start();
$header_written = false;
foreach ($data['result_set'] as $item) {
  $keys = array();
  $vals = array();
  foreach($item as $k => $v) {
    array_push($keys, $k);
    array_push($vals, $v);
  }
  if (!$header_written) {
    fputcsv($f, $keys, ',', '"');
    $header_written = true;
  }
  mb_fputcsv($f, $vals);
  fputcsv($f, $vals, ',', '"');
}
$csvraw = ob_get_clean();
fclose($f);

// バッファを出力
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=$filename");
echo $csvraw;
10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9