我有一个具有以下结构的网页:
<html>
<body>
<div class='title'>
<a></a>
<p></p>
</div>
<div class='title'>
<a></a>
<p></p>
</div>
<div class='title'>
<a></a>
<p></p>
</div>
<div class='title'>
<a></a>
<p></p>
</div>
</body>
</html>页面中还有其他内容,但就这个问题而言,它是不相关的(某种程度上)。
我想做的是用类<a>从每个div中提取title和<p>元素。我已经介绍了许多方法(simple-html-dom、xPath、Regex等)。但是,由于我对PHP的了解有限,我很难理解,向正确的方向推进一点可能会对我有很大的帮助。
所以我的问题是,你会用什么?你能给我举个例子说明你会如何使用它吗。这不一定是愚蠢的证据,只要我有了主意,我就会做剩下的事。
谢谢。
发布于 2014-10-07 10:27:17
是的,您可以在这种特殊情况下使用DOMDocument。
下面是一个粗略的例子:
$markup = "<html>
<body>
<div class='title'>
<a></a>
<p></p>
</div>
<div class='title'>
<a></a>
<p></p>
</div>
<div class='title'>
<a></a>
<p></p>
</div>
<div class='title'>
<a></a>
<p></p>
</div>
</body>
</html>";
$dom = new DOMDocument();
$dom->loadHTML($markup);
$xpath = new DOMXpath($dom);
$elements = array();
$search = $xpath->query('//div[@class="title"]');
foreach($search as $node) {
foreach($node->childNodes as $k => $child) {
if(isset($child->tagName) && ($child->tagName == 'a' || $child->tagName == 'p')) {
$data[$k][] = $child;
// or $child->nodeValue if you want the innertext
}
}
}
echo '<pre>';
print_r($data);或者类似这样的东西,如果你只是期望这个结构总是这样:
$search = $xpath->query('//div[@class="title"]');
foreach($search as $k => $node) {
$a = $xpath->query('//a', $node)->item(0);
$p = $xpath->query('//p', $node)->item(0);
$data[] = array('a' => $a, 'p' => $p);
}发布于 2014-10-07 10:42:40
您也可以使用php,这里有一些代码来帮助
<?php
$filename="nameofhtmlfile.html"
$contents = file_get_contents($filename);
$new_contents = str_replace('<div class=\'title\'><a></a><p></p></div>', '<div class=\'title\'> </div>', $contents);
file_put_contents($filename, $new_contents);
?>使用此php脚本读取html文件的内容,如果html文件变大,则使用php替换语法编辑其内容,您可能需要考虑迭代,而不是将所有内容复制到内存中。
$f = fopen("file","r");
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( (stripos($line,"<div class=\'title\'><a></a><p></p></div>")!==FALSE) ){
$line=preg_replace("<div class=\'title\'><a></a><p></p></div>","<div class=\'title\'> </div>",$line);
}
print $line;
}
fclose($f);
}https://stackoverflow.com/questions/26233732
复制相似问题