0

I'm trying to implement a search filter on a Laravel project. As I'm currently storing all the content of a page together through a WYSIWYG editor, the problem I'm facing now is how to get only the "p" tags on the content of the pages I retrieve from the database. I already tried a few things but nothing is working. Can anyone point me in the right direction? Here is what I'm trying so far:

<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>

Error: Object of class DOMNodeList could not be converted to string (View: /Users/ruirosa/Documents/AptanaStudio3Workspace/Marave4/app/views/search/search.blade.php)

Rui Silva
  • 99
  • 4
  • 12
  • 2
    Have you tried `var_dump($sr_text)`? Have you tried searching for "PHP Get content from DOM element"? If you did you'd find this - http://stackoverflow.com/questions/6859527/how-to-get-tag-content-using-domdocument – Styphon Feb 02 '15 at 17:13
  • Thanks Styphon, you got me on the right track. – Rui Silva Feb 03 '15 at 16:26

1 Answers1

0

It would be work:

<?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);
    }
}

Output:
enter image description here

Also, as "$sr_text" is a iterable/traversable object you can't print out it. You must iterate it.

Read the docs:

The DOMNodeList class
Traversable Interface
Interface NodeList (from W3C WD-DOM-Level-3)

felipsmartins
  • 13,269
  • 4
  • 48
  • 56