Skip to content

Instantly share code, notes, and snippets.

@vuthaihoc
Last active January 16, 2019 10:24
Show Gist options
  • Save vuthaihoc/c6415a7eef3fa944b1592526ef32880b to your computer and use it in GitHub Desktop.
Save vuthaihoc/c6415a7eef3fa944b1592526ef32880b to your computer and use it in GitHub Desktop.
<?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();
});
<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