我真的希望有人花一点时间来检查我的代码。我正在解析一些新闻内容,我可以将初始解析插入到我的数据库中,其中包含新闻 URL 和标题。我想进一步扩展它,传递每个文章链接并解析文章的内容并将其包含在我的数据库中。最初的解析工作非常完美,如下所示:
<?php
include_once ('connect_to_mysql.php');
include_once ('simple_html_dom.php');
$html = file_get_html('http://basket-planet.com/ru/');
$main = $html->find('div[class=mainBlock]', 0);
$items = array();
foreach ($main->find('a') as $m){
$items[] = '("'.mysql_real_escape_string($m->plaintext).'",
"'.mysql_real_escape_string($m->href).'")';
}
$reverse = array_reverse($items);
mysql_query ("INSERT IGNORE INTO basket_news (article, link) VALUES
".(implode(',', $reverse))."");
?>
正如你所看到的,我正在使用PHP 简单 HTML DOM 解析器。 http://simplehtmldom.sourceforge.net/为了扩展,我尝试使用 mysqli 语句,我可以在其中绑定参数,以便所有 html 标签都插入到我的数据库中。我之前已经通过 XML 解析完成了此操作。问题是我不知道如何绑定数组,看看我的代码是否正确,是否可以这样工作......这是整个代码:
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SET NAMES 'utf8'");
include_once ('simple_html_dom.php');
$html = file_get_html('http://basket-planet.com/ru/');
//find main news
$main = $html->find('div[class=mainBlock]', 0);
$items = array();
foreach ($main->find('a') as $m){
$h = file_get_html('http://www.basket-planet.com'.$m->href.'');
$article = $h->find('div[class=newsItem]');
//convert to string to be able to modify content
$a = str_get_html(implode("\n", (array)$article));
if(isset($a->find('img'))){
foreach ($a->find('img') as $img){
$img->outertext = '';}} //get rid of images
if(isset($a->find('a'))){
foreach ($a->find('a') as $link){
$link->href = 'javascript:;';
$link->target = '';}} //get rid of any javascript
if(isset($a->find('iframe'))){
foreach ($a->find ('iframe') as $frame){
$frame->outertext = '';}} //get rid of iframes
@$a->find('object', 0)->outertext = '';
@$a->find('object', 1)->outertext = '';
//modify some more to retrieve only text content
//put entire content into a div (will if statements work here???)
$text_content = '<div>'.$a.'<br>'.
($a->find('object', 0)->data > 0 ? '<a target="_blank" href="'.$a->find('object', 0)->data.'">Play Video</a> ')
($a->find('object', 1)->data > 0 ? '<a target="_blank" href="'.$a->find('object', 1)->data.'">Play Video</a> ')
($a->find('iframe[src*=youtube]', 0)->src > 0 ? '<a target="_blank" href="'.$a->find('iframe', 0)->src.'">Play Video</a> ')
//couple more checks to see if video links are present
.'</div>';
$items[] = '("'.$m->plaintext.'","'.$m->href.'","'.$text_content.'")';
}
//reverse the array so the latest items have the last id
$reverse = array_reverse($items);
$stmt = $mysqli->prepare ("INSERT IGNORE INTO test_news (article, link, text_cont) VALUES (?,?,?)");
$stmt->bind_param ???; //(implode(',', $reverse));
$stmt->execute();
$stmt->close();
?>
因此,逻辑是对于找到的文章的每个 href,我将其传递来解析内容,并尝试将其添加到数组中。我可能有很多错误,但我还无法测试它,因为我不知道如何绑定它以查看它是否有效。而且我也不确定是否可以在 $text_content div 中执行 if 语句...意思是显示“播放视频”(如果存在)。所以,如果有人能花时间和我一起解决这个问题,我将非常感激。
更新:将 $text_content div 中的 if 语句更改为比较运算符。