Last active
January 16, 2019 10:24
-
-
Save vuthaihoc/c6415a7eef3fa944b1592526ef32880b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: hocvt | |
* Date: 1/4/19 | |
* Time: 15:05 | |
*/ | |
ini_set( 'display_errors', 1); | |
require __DIR__ . "/vendor/autoload.php"; | |
use Symfony\Component\DomCrawler\Crawler; | |
$html = <<<HTML | |
<html> | |
<div class="content"> | |
<h2 class="gamma">Excerpt</h2> | |
<p>...content html...</p> | |
</div> | |
<div class="content"> | |
<h2 class="gamma">Excerpt</h2> | |
<p>...more content html...</p> | |
</div> | |
</html> | |
HTML; | |
$crawler = new Crawler($html, 'http://localhost'); | |
// remove all h2 nodes inside .content | |
$crawler->filter('html .content h2')->each(function (Crawler $crawler) { | |
foreach ($crawler as $node) { | |
$new_node = new DOMElement( 'h3'); | |
$new_node->textContent = $node->textContent; | |
$node->parentNode->replaceChild($new_node, $node); | |
// Nếu muốn gán các thuộc tính khác phải gọi sau khi replace child(Node đk gán vào Document cụ thể | |
$new_node->setAttribute( 'class', 'h3'); | |
} | |
}); | |
// output .content nodes with h2 removed | |
$crawler->filter('html .content')->each(function (Crawler $crawler) { | |
echo $crawler->html(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h3 class="h3">Excerpt</h3> | |
<p>...content html...</p> | |
<h3 class="h3">Excerpt</h3> | |
<p>...more content html...</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment