4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

laravelでローカルのXMLファイルをパースしてDBに保存してみる。

Last updated at Posted at 2019-11-17

ローカルのXMLファイルをパースしてDBに保存してみる。

バージョン

$ php -version
PHP 7.3.10 (cli) (built: Sep 30 2019 19:59:06) ( NTS )
$ php artisan -V
Laravel Framework 6.4.0
$ laravel -V
Laravel Installer 2.2.0

XMLデータの中身はこんな感じにしてみました。

test.xml
<?xml version="1.0" encoding="utf-8"?>
<students>
 <student>
  <id>1</id>
  <name>tanaka</name>
  <age>12</age>
 </student>
 <student>
  <id>2</id>
  <name>yamada</name>
  <age>15</age>
 </student>
 <student>
  <id>3</id>
  <name>togashi</name>
  <age>20</age>
 </student>
</students>
 

①データベースの指定

今回はsqliteを使ってみましょう。

$touch database/database.sqlite

データベースが現在mysqlを指定しているのでsqliteに切り替えましょう。(.envファイルです)
※DB_DATABASEはdatabase/database.sqliteのディレクトリを指定してください。
今ディレクトリはpwdコマンドで!

DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=/Users/xxxxxxxxxxx/xxxxx/xxxx/yourapp/database/database.sqlite
DB_USERNAME=root
DB_PASSWORD=

データベースの設定もmysqlからsqliteに変更しましょう。

config/database.php
'default' => env('DB_CONNECTION', 'sqlite'),

一通り設定が終わったらマイグレーション

$php artisan migrate

②テーブルを作成

studentsテーブルを作成しましょう。

$ php artisan make:migration create_students_table
Created Migration: 2019_11_17_011430_create_students_table

作成したマイグレーションファイルにnameとageのカラムを追加しましょう。とりあえず属性はstringで。

/database/migrations/2019_11_17_011430_create_students_table.php
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('name');
            $table->string('age');
        });
    }

再びマイグレーション

$ php artisan migrate
Migrating: 2019_11_17_011430_create_students_table
Migrated:  2019_11_17_011430_create_students_table (0 seconds)

③コントローラーに処理を書く_1

下準備ができたのでいよいよ処理を書いていきます。
まずはコントローラーの作成から

$ php artisan make:controller StudentController
Controller created successfully.

最初に作成したtest.xml(XMLファイル)をapp/storage配下に格納しましょう。

StudentController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function index()
    {
        $contents = file_get_contents(storage_path('test.xml'));
        var_dump($contents);
    }
}

studentコントローラーのルートを生成しましょう。

routes/web.php
Route::get('/student', 'StudentController@index');

それではサーバーを立ち上げてみます。
http://localhost:8000/student にアクセス

$ php artisan serve

XMLファイルの中身がブラウザ上に確認できましたか?

④コントローラーに処理を書く_2

コントローラーにXMLファイルのパース処理を記載していきましょう。

StudentController.php
class StudentController extends Controller
{
    public function index()
    {
        $contents = file_get_contents(storage_path('test.xml'));
        $xmlObject = simplexml_load_string($contents);
        $xmlArray = json_decode( json_encode( $xmlObject ), TRUE );
        $xmlArray = $xmlArray['student'];
    }
}

4行目の処理ですが、
studentsの連想配列の中のstudentを参照し、DBに保存する必要があります。

$xmlArray = $xmlArray['student'];

eval(\ Psy\Sh()); でパース後の中身を見てみましょう。

StudentController.php
class StudentController extends Controller
{
    public function index()
    {
        $contents = file_get_contents(storage_path('test.xml'));
        $xmlObject = simplexml_load_string($contents);
        $xmlArray = json_decode( json_encode( $xmlObject ), TRUE );
        $xmlArray = $xmlArray['student'];
        eval(\ Psy\Sh());
    }
}

$xmlArrayの中身は。。。

$xmlArray
=> [
     [
       "id" => "1",
       "name" => "tanaka",
       "age" => "12",
     ],
     [
       "id" => "2",
       "name" => "yamada",
       "age" => "15",
     ],
     [
       "id" => "3",
       "name" => "togashi",
       "age" => "20",
     ],
   ]

いい感じに入ると思います。
それでは最後にstudentsのテーブルに保存しましょう。

StudentController.php
class StudentController extends Controller
{
    public function index()
    {
        $contents = file_get_contents(storage_path('test.xml'));
        $xmlObject = simplexml_load_string($contents);
        $xmlArray = json_decode( json_encode( $xmlObject ), TRUE );
        $xmlArray = $xmlArray['student'];
        \DB::table('students')->insert($xmlArray);
    }
}

それではサーバーを立ち上げてみます。
http://localhost:8000/student にアクセス

⑤DBを確認

$ cd database
$ sqlite3 database.sqlite

そういえばちゃんとDBにテーブルがあるか確認・・・

sqlite> .tables
failed_jobs      password_resets  users          
migrations       students

テーブルは作成されていたのでstudentsテーブルのid,name,ageカラムを指定して出力。

sqlite> select id, name, age from students;
1|tanaka|12
2|yamada|15
3|togashi|20

3名のデータが出力されていればOK。無事データベースに保存されていました。
今回はここまで。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?