我创建了一个php解析器来编辑由CMS创建的html。我要做的第一件事是解析用于添加模块的自定义标记。
之后,如果需要,链接,图像等内容将被更新,更改或w/e。这一切都有效。
现在我注意到,当自定义标记被替换为 html 时,生成的模块不会由其余操作处理此 html。
例如,所有 href 为/pagelink-001 的链接都将替换为当前页面的实际链接。这适用于初始加载的 html,而不是替换的标记。下面我有一个简短的代码版本。我尝试用saveHtml()
保存它,并用loadHtml()
和类似的东西加载它。
我猜这是因为加载的 html $doc没有这样更新。
我的代码:
$html = '<a href="/pagelink-001">Link1</a><customtag></customtag>';
// Load the html (all other settings are not shown to keep it simple. Can be added if this is important)
$doc->loadHTML($html);
// Replace custom tag
foreach($xpath->query('//customtag') as $module)
{
// Create fragment
$return = $doc->createDocumentFragment();
// Check the kind of module
switch($module)
{
case 'news':
$html = $this->ZendActionHelperThatReturnsHtml;
// <div class="news"><a href="/pagelink-002">Link2</a></div>
break;
}
// Fill fragment
$return->appendXML($html);
// Replace tag with html
$module->parentNode->replaceChild($return, $module);
}
foreach($doc->getElementsByTagName('a') as $link)
{
// Replace the the /pagelink with a correct link
}
在此示例中Link1
href 被替换为正确的值,但Link2
不是。 Link2 确实正确显示为链接,并且一切正常。
关于我如何使用新 html 更新$doc的任何方向,或者如果这确实是问题所在,那就太棒了。或者请告诉我我是否完全错了(以及在哪里寻找(!
提前感谢!!
看来我是对的,返回的字符串是字符串而不是 html。我在代码中发现了我在某个时候实现的 @Keyvan innerHtml 函数。这导致我的函数是这样的:
// Start with the modules, so all that content can be fixed as well
foreach($xpath->query('//customtag') as $module)
{
// Create fragment
$fragment = $doc->createDocumentFragment();
// Check the kind of module
switch($module)
{
case 'news':
$html = htmlspecialchars_decode($this->ZendActionHelperThatReturnsHtml); // Note htmlspecialchars_decode!
break;
}
// Set contents as innerHtml instead of string
$module->innerHTML = $html;
// Append child
$fragment->appendChild($module->childNodes->item(0));
// Replace tag with html
$module->parentNode->replaceChild($fragment, $module);
}