【问题标题】:php dom replacedChild, save as html and continue parsingphp dom 替换Child,另存为html,继续解析
【发布时间】:2016-05-10 11:58:59
【问题描述】:

我创建了一个 php 解析器来编辑由 CMS 创建的 html。我做的第一件事是解析一个自定义标签以添加模块。

之后,如果需要,链接、图像等内容会根据需要进行更新、更改或 w/e。这一切都有效。

现在我注意到,当自定义标签被替换为 html 时,生成此 html 的模块不会被其余操作处理。

例如;所有带有 /pagelink-001 的 href 的链接都将替换为当前页面的实际链接。这适用于初始加载的 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 的说明,或者如果这确实是问题所在,那就太棒了。或者,如果我完全错了(以及在哪里看),请告诉我!

提前致谢!!

【问题讨论】:

    标签: php dom replace


    【解决方案1】:

    看来我是对的,返回的字符串是字符串而不是 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多