【问题标题】:Extract DIV from XHTML with simpleHTMLDom and then print out使用 simpleHTMLDom 从 XHTML 中提取 DIV,然后打印出来
【发布时间】:2013-06-09 23:39:58
【问题描述】:

任务 - 使用 ID 抓取 DIV 标记内的内容,然后返回 XHTML。 我正在使用“PHP 简单 HTML DOM 解析器”

示例简化代码:

<html><head></head>
<body>
<h1>Head</h1>
<div class="page">
<div id="content">
<h2>Section head</h2>
<p>Text</p>
</div>
<div id="footer">Footer text</div>
</div>
</body>
</html>

我可以通过以下方式获得内容:

$content = $html->find('#content');

$content 现在是一个 simpleDOM 对象 一个数组(已更正)。

我如何将它转换回 XHTML,所以我只有:

<div id="content">
<h2>Section head</h2>
<p>Text</p>
</div>

谢谢

【问题讨论】:

    标签: simpledom


    【解决方案1】:

    你试过了吗:

    // Dumps the internal DOM tree back into string 
    $str = $content->save();
    

    参考: http://simplehtmldom.sourceforge.net/manual.htm

    【讨论】:

    • 我已经更正了我的问题。 $html->find('#content') 返回一个数组而不是一个对象,所以不能使用 $content->save();
    【解决方案2】:

    这工作正常:

    // Sample HTML string
    $html_str = '<html><head></head><body><h1>Head</h1><div class="page"><div id="content"><h2>Section head</h2><p>Text</p></div><div id="footer">Footer text</div></div></body></html>';
    
    // Create new DOM object
    $dom = new DOMDocument();
    
    // $html_str is HTML (can load from URL, if your host allows)
    $dom->loadHTML($html_str);
    
    // Get DIV id="content"
    $element = $dom->getElementById('content');
    
    // use save XML as input is XHTML.
    echo $dom->saveXML($element);
    
    // cleanup to prevent memory leak
    $dom->clear(); 
    unset($dom);
    

    如果在另一个模板中使用,您必须添加正确的字符集才能正确显示字符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多