使用 PHP cURL 从网站获取一些文本并存储在 MySQL

Using PHP cURL to get some text from website and store in MySQL

为了完成这项工作,我已经四处寻找了一段时间,但似乎我一个人做不到。我正在使用 cURL 从网站获取一些信息并将这些信息存储在 MySQL 数据库中。我现在拥有的是以下代码:

$target_url = "[http:\[//\]iliria98\[.\]com][1]"; //delete [ and ] to get the url correctly
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';

// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
$html= curl_exec($ch);
if (!$html) {
    echo "<br />cURL error number:" .curl_errno($ch);
    echo "<br />cURL error:" . curl_error($ch);
    exit;
}

// parse the html into a DOMDocument
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML($html);
libxml_clear_errors();
$selector = new DOMXPath($document);
//$anchors = $selector->query('//div[@class="single"]/div[2]');
$anchors = $selector->query('//div[@class="single"]/div');
foreach($anchors as $div) { 
    $text = $div->nodeValue;

    $valuta_arr=explode(',', $text);
    var_dump($valuta_arr);
    echo $text;
}

并且,输出不正确,因为它从网站获取所有货币代码,但货币值仅来自第一行,来自 USD。 我想要的是从指定的 url 上的 html table 获取值,并将这些值插入数据库中的每种货币,其中数据库 table 看起来像这个:

id
currency
sell
buy
date

直到 mysql 插入代码我才得到,因为我已经努力了 3 天才能首先从该网站获取信息。 希望有人可以帮助我。 谢谢大家。

如果您尝试通过 curl http://iliria98.com 从控制台获取此页面,您会发现此小部件由 js 脚本填充:

$('div#usd1').append('<div style="position: absolute; background: transparent; width: 100%; height: 100%; left: 0; top: 0; z-index: 9999;"></div>')
$(".kursiweb .single").eq(0).find("div").eq(1).html("114<sup>.20</sup>");  $(".kursiweb .single").eq(0).find("div").eq(2).html("116");

等等...

因此,您只能从源代码 HTML 中的此脚本获取所需的数据,您是从 curl 获取的,而不是从 DOM 文档获取的,只是因为 curl 没有任何 JS 引擎。

另一种方法 - 使用类似 PhantomJS

的方法