doubi1818 2017-09-15 22:40
浏览 227
已采纳

Laravel - 将.txt文件保存到mySQL数据库

I have been struggling to create something that can save txt files into a mySQL database. I have managed to create something that saves JSON files but not txt files.

Here is the txt file in question: http://celestrak.com/NORAD/elements/sbas.txt. This txt file contains a few satellites with their data. Each satellite has exactly three lines, no exceptions. So, for example here is one satellite:

AOR-E (EGNOS/PRN 120)   
1 24307U 96053A   17257.68868765 -.00000150  00000-0  00000-0 0  9992
2 24307   2.8040  77.2609 0004175 104.1816  44.8421  1.00271450 76939

The first lines tells us the satellite name. The next two lines give us some parameters, which always start with the numbers 1 and 2. This format will not change - the name on line 0 and the two lines after it, which start in 1 or 2.

What I want to be able to do is to create a row for each satellite - with the columns object_name for line 0, tle_line1 for line 1 and tle_line2 for line 2.

I have managed to create something that saves data from a JSON format into the SQL database. Maybe some can be deviated from that?

I am using Laravel and Guzzle for the HTTP requests:

$api = new Client([
    'base_uri' => 'http://celestrak.com',
]); 
$response = $api->get('jsonlocater');
$data = json_decode($response->getBody()->getContents(), true);
    foreach ($data as $attributes) {
    $attributes = array_change_key_case($attributes, CASE_LOWER);
    Satellites::create($attributes);
}
  • 写回答

1条回答 默认 最新

  • duan0531 2017-09-15 22:58
    关注

    First of all, I'm not sure what is your response format but using vanilla PHP you may do something like the following to fetch the contents in array:

    $url = 'http://celestrak.com/NORAD/elements/sbas.txt';
    $lines = file($url, FILE_IGNORE_NEW_LINES);
    $arrays = array_map(function($array) {
        $columns = ['object_name', 'tle_line1', 'tle_line2'];
        return array_combine($columns, array_map('trim', $array));
    }, array_chunk($lines, 3));
    

    Now, if you dd($arrays) the result then you'll get something like the following:

    enter image description here

    From this result, you should be easily able to create entries in your database. Each array in image should be an entry/row in your database table. For example:

    \DB::table('table_name')->insert($arrays);
    

    Note that, if you've timestamps (created_at & updated_at) in your table then you've to add those fields in each array when generating the arrays.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试