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.

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法