Php 将div的内容获取到某一点
我使用以下代码获取所有段落标记:Php 将div的内容获取到某一点,php,Php,我使用以下代码获取所有段落标记: // Product Description $html = file_get_html('http://domain.local/index.html'); $contents = strip_tags($html->find('div[class=product-details] p')); 我怎么能说抓取X个段落,直到它到达第一个ul 您可以根据上述要求使用以下代码:- <?php $html = file_get_html('http:/
// Product Description
$html = file_get_html('http://domain.local/index.html');
$contents = strip_tags($html->find('div[class=product-details] p'));
我怎么能说抓取X个段落,直到它到达第一个ul
您可以根据上述要求使用以下代码:-
<?php
$html = file_get_html('http://domain.local/index.html');
$detailTags = $html->find('div[class=product-details] *');
$contents = "";
foreach ($detailTags as $detailTag){
// these condition will check if tag is not <p> or it's <ul> to break the loop.
if (strpos($detailTag, '<ul>') === 0 && strpos($detailTag, '<p>') !== 0) {
break;
}
$contents .= strip_tags($detailTag);
}
// contents will contain the output required.
echo $contents;
?>
编辑:Nandal的代码将适用于您,因为它不会强制您更改库
如果您不想依赖第三方库,那么您可以使用PHP的DOM文档特性,您需要为其启用扩展
您可以查看下面的代码,该代码将打印段落,直到找到任何其他标记:
<?php
$html = new DOMDocument();
$html->loadHTML("<html><body><p>Paragraph 1</p><p> Paragraph 2</p><p> Paragraph 3</p><ul> <li> List item 1 </li> <li> List item 2 </li> </ul><blockquote> Quote 1</blockquote><blockquote> Quote 2</blockquote><blockquote> Quote 3</blockquote><p> Paragraph 4</p><p> Paragraph 5</p></body></html>");
$xpath = new DOMXPath($html);
$nodes = $xpath->query('/html/body//*');
foreach($nodes as $node) {
if($node->nodeName != "p") {
break;
}
print $node -> nodeValue . "\n";
}
在内容上使用substr和STRPO如何?@nandal如何?请注意,段落的数量是可变的。你能粘贴url吗?@nandal这是一个本地网站抱歉,我想作为另一个退路,如果它遇到一个类似的问题,我能破坏它吗?如果strpos$detailTag,==0&&strpos$detailTag,“”!==0&&strpos$detailTag,==0{
Paragraph 1 Paragraph 2 Paragraph 3
<?php
$html = new DOMDocument();
$html->loadHTML("<html><body><p>Paragraph 1</p><p> Paragraph 2</p><p> Paragraph 3</p><ul> <li> List item 1 </li> <li> List item 2 </li> </ul><blockquote> Quote 1</blockquote><blockquote> Quote 2</blockquote><blockquote> Quote 3</blockquote><p> Paragraph 4</p><p> Paragraph 5</p></body></html>");
$xpath = new DOMXPath($html);
$nodes = $xpath->query('/html/body//*');
foreach($nodes as $node) {
if($node->nodeName != "p") {
break;
}
print $node -> nodeValue . "\n";
}