From a8d2e06387e60ef7f861baf204fdcaba8aec645f Mon Sep 17 00:00:00 2001 From: Marc Date: Sun, 21 Apr 2013 02:11:42 +0200 Subject: [PATCH] Added html method into Crawler class * This method allow to get html inside desired element * New method is tested --- src/Symfony/Component/DomCrawler/Crawler.php | 22 +++++++++++++++++++ .../DomCrawler/Tests/CrawlerTest.php | 12 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 21ab0bdd8bd3f..14e49da2080b8 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -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. * diff --git a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php index 835c4d2473973..36e197d06fd09 100644 --- a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php @@ -319,6 +319,18 @@ public function testText() } } + public function testHtml() + { + $this->assertEquals('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');