Skip to content

Commit

Permalink
tec: Provide a Dom::html method
Browse files Browse the repository at this point in the history
  • Loading branch information
marienfressinaud committed Jul 29, 2023
1 parent 72f0d71 commit a2bd429
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/SpiderBits/src/Dom.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,28 @@ public function list(): mixed
}
}

/**
* Return the HTML of the current selected node(s) as a string
*/
public function html(): string
{
if ($this->nodes_selected) {
$htmls = [];
foreach ($this->nodes_selected as $node) {
$htmls[] = $this->dom->saveHTML($node);
}
return implode("\n", $htmls);
} else {
$html = $this->dom->saveHTML();

if ($html === false) {
$html = '';
}

return $html;
}
}

/**
* Return the content of the current selected node(s) as a string
*/
Expand Down
30 changes: 30 additions & 0 deletions tests/lib/SpiderBits/DomTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,36 @@ public function testTextWithMixOfHtmlEntitiesAndUtf8(): void
$this->assertSame("Site d'information français", $text);
}

public function testHtml(): void
{
$dom = Dom::fromText(<<<HTML
<div>Hello World!</div>
HTML, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$html = $dom->html();

$this->assertSame("<div>Hello World!</div>\n", $html);
}

public function testHtmlWithSelectedNodes(): void
{
$dom = Dom::fromText(<<<HTML
<div>
<p>Hello</p>
</div>
<div>
<p>World!</p>
</div>
HTML);
$p_nodes = $dom->select('//p');

$this->assertNotNull($p_nodes);

$html = $p_nodes->html();

$this->assertSame("<p>Hello</p>\n<p>World!</p>", $html);
}

public function testSelect(): void
{
$dom = Dom::fromText(<<<HTML
Expand Down

0 comments on commit a2bd429

Please sign in to comment.