【问题标题】:PHP simple HTML Dom select inner text only not child inne rtextPHP简单的HTML Dom只选择内部文本而不是子内部文本
【发布时间】:2014-08-13 08:25:19
【问题描述】:

我正在使用 PHP 简单的 HTML DOM 类来解析 html。 我想选择带有id="content"内部文本的div,但是当我调用$selecrot->plaintext时,它也会返回子div文本

示例 HTML

<div id="content">
Hello World.
<div id="sub-content1">
Text I don't want to select.
</div>
<div id="sub-content2">
Text I don't want to select
</div>
</div>

示例代码

//suppose $html contains above html
$selector = $html->find("div#content", 0); 
echo $selector->innertext; 
//it outputs "Hello World. Text I don't want to select. Text I don't want to select"
//but 

我只想要“Hello World”

【问题讨论】:

  • 这个问题与jquery无关。不是重复的问题

标签: php html dom


【解决方案1】:
include_once('simple_html_dom.php');
$html = new simple_html_dom();

$text = '<div id="content">
Hello World.
<div id="sub-content1">
Text I don\'t want to select.
</div>
<div id="sub-content2">
Text I don\'t want to select
</div>
</div>';

$html->load($text);
$selector =$html->find("div#content",0)->find("*");
foreach($selector  as $node){
$node->outertext = '';
}
$html->load($html->save()); 
$selector =$html->find("div#content",0);
echo $selector->innertext;

【讨论】:

  • 提供一些解释
  • 第1步:查找选择器的所有节点,第2步:NULL所有节点,第3步:重新加载简单的HTML DOM,第3步选择器内容为'
    Hello World。
    '
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 2012-08-17
  • 2019-11-04
相关资源
最近更新 更多