LEN

PHP 抓取币安BTC正向合约每小时K线创建csv文件
<?php $context = stream_context_create(array( ...
扫描右侧二维码阅读全文
28
2019/10

PHP 抓取币安BTC正向合约每小时K线创建csv文件

<?php

$context = stream_context_create(array(
        "http" => [
            "timeout" => 3
        ],
    ));
$curTime = (string)(time()) .'000';
$isFirst = true;
do{
    $isRun =  true;
    $data = file_get_contents("https://fapi.urbn1w.cn/fapi/v1/klines?symbol=BTCUSDT&interval=1h&endTime={$curTime}", false, $context);


    echo $curTime,"字节", strlen($data),PHP_EOL;

    $curTime =    $curTime -1800000000;
    if (!$data) {
        echo '失败',PHP_EOL;
        $isRun = false;
        break;
    }

    $dataArr = json_decode($data, true) ?? [];

    $newDataArr = [];
    foreach ($dataArr as $ke => $v) {
        
        if (empty($v[6])) continue;

        $newDataArr[$v[6]] = [
            'open' => $v[1],
            'close' => $v[4],
            'high' => $v[2],
            'low' => $v[3],
            'time' => date('YmdH', ceil($v[0]/1000)),
        ];
    }

    create_excel($newDataArr, './btc_usdt', $isFirst );
    $isFirst = false;
    sleep(1);
}while ($isRun);

 // 创建表格文件 xls,csv
function create_excel($data = array(), $file_name = '', $isFirst = true, $file_type = 'csv')
{
    $file_name .= date('Ymd');
    $split = ",";
    if ($file_type == 'xls') {
        $split = "\t";
    }
    $output = '';
   
   if ($isFirst) {
        $first = reset($data);
        foreach ($first as $key => $value) {
            $output .= $key . $split;
        }
    }

    $output .= "\r\n";
    foreach ($data as $value) {
        foreach ($value as $v) {
            $output .= $v . $split;
        }
        $output = trim($output, ",");
        $output .= "\r\n";
    }
    $fileName = $file_name . "." . $file_type;

    file_put_contents($fileName, $output, FILE_APPEND);
}
最后修改:2019 年 10 月 28 日 01 : 56 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论