-1

我有一个 php 脚本,可以解析 html 页面内容链接和视图,但我需要知道如何将这些内容存储在 sqlite3 数据库中,有什么建议吗?

include_once('simple_html_dom.php'); //PHP Simple HTML DOM Parser library  
$html = file_get_html('www.website.com');  

// Find all article blocks
foreach($html->find('div.postbody') as $article) {
 $item['details'] = $article->find('div.content', 0)->innertext;
 $articles[] = $item;
}
print_r($articles); 

try {

$db = new SQLite3('db/mysqlitedb.db');
$db->exec// what type of table should i create
$db->exec// how tell db to store html content from $articles
$result = $db->query('SELECT bar FROM gg');
var_dump($result->fetchArray());

    /* Close connections to Database */
    $db = NULL;
}

catch( PDOException $e ) 
{

    /* Print Error-Messages */
    echo $e->getMessage();
} 
4

1 回答 1

1

通常,您将只创建一个表来存储所有片段,而不是每个片段一个表。因此,您在该表中需要的最少字段是用于标识片段和片段本身的内容。根据您的要求,您可能需要添加额外的字段,例如插入片段的日期时间、插入者的用户 ID 等。

该片段将存储为TEXT(可以包含文本信息的大型对象数据类型),为简单起见,我将使用INTEGER字段作为标识符。根据您想要检索片段的方式,您还可以使用短字符串,例如VARCHAR

CREATE TABLE fragments(
    identifier INTEGER,  -- a unique identifier
    fragment TEXT        -- the fragment
);

接下来,在您包含在问题中的代码行集合中,您使用的是包装在 PDO 异常中的本机 SQLite 驱动程序。这是否会正常工作是非常值得怀疑的。我建议你坚持 PDO 和准备好的陈述。甚至不要考虑使用拼凑在一起的文字 INSERT 语句,尤其是在插入 html 片段的这种情况下。或者在任何其他情况下,preparedstatements 是针对 sql 注入攻击和相关恶作剧的唯一防水和防弹防御。

// open the db.  as this is relatively costly it's typically done outside any loops 
// in the rest of the code
$dbh=new PDO('sqlite:./db/mysqlitedb.db') or die("failed to connect to db");

// let's assume $item contains the fragment and $identifier 
// was initialized with some key value in the mean time
try{
   $stmt = $dbh->prepare("INSERT INTO fragments (identifier, fragment) VALUES (?, ?)");
   $stmt->bindParam(1, $identifier);
   $stmt->bindParam(2, $item);
   $stmt->execute();
} catch(PDOException $e) {
   echo $e->getMessage();
}

这就是基本设置。想不出这些片段的唯一数字键?没问题,将标识符的类型更改VARCHAR为表定义中的。

于 2012-10-21T17:48:03.467 回答