【问题标题】:How can I send scraped DATA to Mysql table with LARAVEL如何使用 LARAVEL 将抓取的数据发送到 Mysql 表
【发布时间】:2019-02-23 04:12:01
【问题描述】:

我用 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 发送数据?
  • 我不知道如何使用 laravel 发送抓取的数据。这就是问题的开始。我将 laravel 连接到数据库并制作表格,但不知道如何将抓取的数据发送到我创建的表格中。

标签: php mysql laravel scrape


【解决方案1】:

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

首先,您可以创建一个表(根据 cmets,您已经完成了)

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

您的应用程序的数据库配置位于 config/database.php。在此文件中,您可以定义所有数据库 连接,以及指定应该使用哪个连接 默认。大多数受支持的数据库系统的示例是 在此文件中提供。

然后使用 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

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 2013-05-16
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2018-07-09
    • 2022-11-27
    相关资源
    最近更新 更多