我目前正在过渡过程中,我想对我现有的网站进行CMS。直到现在(几年来),我一直在生成和保存完整的html文件,我想将这些页面的内容存储在数据库中。我认为,我的运气是,我想从每个html中提取的两个元素在一个html文件中是唯一的,在所有文件中都是相同的。我试过这个:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$string= file_get_contents($entry);
$pattern = "/<h1>(.*?)<'/h1>/";
preg_match_all($pattern, $string, $uname);
$pattern = '/<p class='"user_info'"><strong>(.*?)<'/strong><'/p>/';
preg_match_all($pattern, $string, $udesc);
echo "NAME: ".$uname[1][0]."<br>";
echo "DESC: ".$udesc[1][0]."<br>";
//MYSQL SAVING WILL GO HERE
}
}
closedir($handle);
}
上面的代码提取了(h1)NAME(/h1)(想象一下(==<and)===>)部分,但没有提取(p class="user_info")(strong)CONTENT(/strong)(/p)部分,它只是空白。
我也尝试过不同的方法:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$string= file_get_contents($entry);
$doc = new DOMDocument();
$doc->loadHTML($string);
$h1 = $doc->getElementsByTagName('h1')->item(0)->textContent;
echo "NAME: ".$h1."<br>";
$p = $doc->saveHtml($doc->getElementsByTagName('p')->item(0)); // $p = $doc->getElementsByTagName('p')->item(0)->textContent; loads content, just without html tags, so I can not use it... :S
echo "DESC: ".$p."<br>";
//MYSQL SAVING WILL GO HERE
}
}
closedir($handle);
}
上面的代码可以工作,但并不像预期的那样。我需要一段完整的HTML代码,而不仅仅是文本。我也尝试过$doc->savehtml(),但仍然一无所获。
请帮忙,并提前表示感谢!
删除->textContent
$h1 = $doc->saveHtml($doc->getElementsByTagName('h1')->item(0));
echo "NAME: ".$h1."<br>";
$p = $doc->saveHtml($doc->getElementsByTagName('p')->item(0));