doubi1818
doubi1818
2017-09-15 22:40

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 duan0531 4年前

    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.

    点赞 评论 复制链接分享

为你推荐