搜索

首页  >  问答  >  正文

将HTML DOM结果存储至MySQL数据库

我试图将抓取的数据存储到我的数据库中。只是将结果输出,所以抓取是正常的。但是在定义变量并将其传递给mysql-insert时肯定有错误。我收到消息“成功创建新记录”。变量的结果为空,日期是存在的。

<?php

$html = file_get_contents('https://www.marketwatch.com/market-data/us?mod=market-data-center');

$scriptDocument = new DOMDocument();

libxml_use_internal_errors(TRUE); 

if(!empty($html)){ 

    $scriptDocument->loadHTML($html);

    libxml_clear_errors(); 

    $scriptDOMXPath = new DOMXPath($scriptDocument);
    $scriptRow = $scriptDOMXPath->query('//th[starts-with(text(), "ISSUES:")]//following::td[6]');if($scriptRow->length > 0){foreach($scriptRow as $row){echo $row->nodeValue;}} // echo result works
    $scriptRow = $scriptDOMXPath->query('//th[starts-with(text(), "ISSUES:")]//following::td[6]');if($scriptRow->length > 0){foreach($scriptRow as $row){$row->nodeValue = $nasdaq_dec;}} // defining variable does not work

};

    $host_name = '';
    $database = '';
    $user_name = '';
    $password = '';
    
    try {
    $conn = new PDO("mysql:host=$host_name; dbname=$database;", $user_name, $password);      
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO `morgenroutine` (date,nasdaq_dec)
    VALUES (NOW(), '$nasdaq_dec')";

    $conn->exec($sql);
    echo "成功创建新记录";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;

?>
P粉549986089P粉549986089445 天前565

全部回复(1)我来回复

  • P粉269530053

    P粉2695300532023-09-16 09:28:43

    现在我明白了!我在mysql中将格式更改为"text",并将行更改为: $scriptRow = $scriptDOMXPath->query('//th[starts-with(text(), "ISSUES:")]/following::td[6]');if($scriptRow->length > 0){foreach($scriptRow as $row){$nasdaq_dec = $row->nodeValue;}}

    回复
    0
  • 取消回复