Skip to content

Added html method into Crawler class #7750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Symfony/Component/DomCrawler/Crawler.php
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,28 @@ public function text()
return $this->getNode(0)->nodeValue;
}

/**
* Returns the html of the first node of the list.
*
* @return string The node html
*
* @throws \InvalidArgumentException When current node is empty
*/
public function html()
{
if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}

$html = '';
foreach ($this->getNode(0)->childNodes as $child) {

$html .= $child->ownerDocument->saveXML($child);
}

return str_replace('
', '', $html);
}

/**
* Extracts information from the list of nodes.
*
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,18 @@ public function testText()
}
}

public function testHtml()
{
$this->assertEquals('<img alt="Bar"/>', $this->createTestCrawler()->filterXPath('//a[5]')->html(), '->html() returns the html of the first element of the node list');

try {
$this->createTestCrawler()->filterXPath('//ol')->html();
$this->fail('->html() throws an \InvalidArgumentException if the node list is empty');
} catch (\InvalidArgumentException $e) {
$this->assertTrue(true, '->html() throws an \InvalidArgumentException if the node list is empty');
}
}

public function testExtract()
{
$crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
Expand Down