Skip to content

Instantly share code, notes, and snippets.

@JosephDuffy
Created July 15, 2013 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosephDuffy/6001567 to your computer and use it in GitHub Desktop.
Save JosephDuffy/6001567 to your computer and use it in GitHub Desktop.
PHP Simple HTML DOM Parser bug?
<?php
require 'simple_html_dom.php';
class Page
{
protected $html;
public function __construct()
{
$startHTML = '<!doctype html>
<html>
<head></head>
<body>
<div id="child">I am the contents of child<br></div>
<div id="replaceMe">ReplaceMe1 ReplaceMe2 ReplaceMe3</div>
</body>
</html>
';
// $this->html = str_get_html($startHTML, true, false);
$html = new \simple_html_dom();
$html->load($startHTML, true, false);
$this->html = $html;
}
public function replace($reSave = false)
{
preg_match_all('/(ReplaceMe([0-9]+))/', $this->html->find('html', 0)->outertext, $replaces);
for ($i = 0; $i < count($replaces[0]); $i++) {
// Get the text that's going to replace the content
$renderText = $this->render($i);
// Get the old HTML so we can manipulate it
$oldHTML = $this->html->find('html', 0)->outertext;
// Replace the found text with the new content
$newHTML = preg_replace('/' . preg_quote($replaces[0][$i]) . '/', $renderText, $oldHTML);
if ($reSave) {
$html = new \simple_html_dom();
$html->load($newHTML, true, false);
$this->html = $html;
// $this->html = str_get_html($newHTML, true, false);
} else {
$this->html->find('html', 0)->outertext = $newHTML;
}
}
echo $this->html->save();
}
public function render($i)
{
$this->html->find('html', 0)->find('#child', 0)->innertext .= 'I am added by the renderer ' . $i . '<br>';
return 'I am the return value from the renderer ' . $i . '<br>';
}
}
$page = new Page();
$page->replace();
unset($page);
$page = new Page();
$page->replace(true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment