我正在尝试在Laravel项目上实现搜索过滤器。由于我目前通过WYSIWYG编辑器将页面的所有内容存储在一起,我现在面临的问题是如何只从我从数据库中检索的页面内容中获取“p”标签。我已经尝试了一些东西,但没有任何工作。谁能指出我正确的方向?这是我到目前为止所做的:
<div id="page-content" class="container">
@foreach($searchResults as $searchResult)
<div class="searchResult_div col-xs-12">
<div class="col-xs-9 col-sm-10 search-result-body">
<?php
$sr = HTML::decode($searchResult['body'], 450, "...");
$dom = new DOMDocument();
@$dom->loadHTML($sr);
$sr_text = $dom->getElementsByTagName("p");
echo $sr_text;
?>
</div>
</div>
@endforeach
</div>
错误:类DOMNodeList的对象无法转换为字符串(查看:/Users/ruirosa/Documents/AptanaStudio3Workspace/Marave4/app/views/search/search.blade.php)
答案 0 :(得分:0)
这将是有效的:
<?php
$html = <<<HTML
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="container">
<p>text content</p>
<section>
<div>
<p>inner text</p>
</div>
</section>
</div>
</body>
</html>
HTML;
$dom = new DomDocument();
@$dom->loadHTML($html);
$para = $dom->getElementsByTagName('p'); #DOMNodeList
if ($para instanceof DOMNodeList) {
foreach ($para as $node) {
# $node is a DOMElement instance
printf ("Node name: %s\n", $node->nodeName);
printf ("Node value: %s\n", $node->nodeValue);
}
}
输出:
另外,作为&#34; $ sr_text&#34;是一个可以打印出来的可迭代/ traversable对象。你必须迭代它。
阅读文档:
The DOMNodeList class
Traversable Interface
Interface NodeList (from W3C WD-DOM-Level-3)