php - 如何使用 LARAVEL 将抓取的数据发送到 Mysql 表

标签 php mysql laravel scrape

我用 php 抓取了一些数据,我想将它从 Laravel 发送到 Mysql。我连接到 mysql 但我不知道如何发送它。

这是我抓取的代码;

$servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "laravel-test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) 
    {

        die("Connection failed: " . $conn->connect_error);

    } 

    $curl = curl_init();
    curl_setopt($curl,CURLOPT_URL,"https://suumo.jp/ms/shinchiku/osaka/sa_osaka/");
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1); 
    $sonuc = curl_exec($curl); 

    preg_match_all('@<div class="cassette-price">(.*?)</div>@si',$sonuc, $new);
    preg_match_all('@<ul class="cassette-plan">(.*?)</ul>@si',$sonuc, $info);
    preg_match_all('@<div class="cassette-header">(.*?)</div>@si',$sonuc, $name);


    $name = $name[0];
    $new = $new[0];
    $info = $info[0];


    for($i=0; $i < count($info);$i++)
    {
    echo $name[$i];
    echo $info[$i]; 
    echo $new[$i];  
    }

感谢帮助!!!

顺便说一句,我正在使用 laravel 5.7。

最佳答案

据我了解,您可以将数据添加到常规表中

首先,你可以创建一个表(你已经做了,根据评论)

然后给 Laravel 添加配置 [ https://laravel.com/docs/5.7/database]

The database configuration for your application is located at config/database.php. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for most of the supported database systems are provided in this file.

然后使用Laravel数据库添加数据

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show a list of all of the application's users.
     *
     * @return Response
     */
    public function index()
    {
      for($i=0; $i < count($info);$i++)
      {
        DB::insert('insert into users (name, info, new)
        values (?, ?, ?)', [1, $name[$i], $info[$i], $new[$i] ]);

您还可以将数据添加到数组中,然后插入一次:

for($i=0; $i < count($info);$i++)
{
           $data[] =[
                    'name' => $name[$i],
                    'info' => $info[$i],
                    'news' => $news[$i],
                   ];  
}
DB::insert($data);

(参见 Insert Multiple Records At Once With Laravel)

关于php - 如何使用 LARAVEL 将抓取的数据发送到 Mysql 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52398179/

相关文章:

PHP : Not getting correct date difference

laravel - 在每个成功的 Laravel Mix 构建中执行 artisan 命令

javascript - 如何在 Instagram 上找到当天最受欢迎的图片?

php - 为什么这个 PHP-MySQL 代码不能正常工作?

mysql - 配置数据库数据库连接到 MySQL RDS : Timed out after 5000 milliseconds

mysql - 如何确定一个人是否在 SQL 中的特定日期注册

php - 带有额外参数的策略

javascript - JS 文件无法访问 laravel 变量

php - sms api 无法在本地计算机中工作,但如果放置在托管服务器中则可以工作

mysql - Mac Os rake 数据库 :create through error with qt and mysql dependence