將HTML DOM結果儲存至MySQL資料庫
P粉549986089
P粉549986089 2023-09-15 23:41:06
0
1
592

我試圖將抓取的資料儲存到我的資料庫中。只是將結果輸出,所以抓取是正常的。但是在定義變數並將其傳遞給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粉549986089
P粉549986089

全部回覆(1)
P粉269530053

現在我明白了!我在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;}}

#
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板