PHP简单的HTML DOM解析器问题

时间:2012-02-22 14:57:44

标签: php html

我有一段像这样的HTML代码:

      <a>
             <img scr=""/>some text here...
      </a>

      <a>
             <img scr=""/>some text here...
      </a>

我需要在这里得到一些文字......

我是这样想的:                       让我们说上面的部分是一个html dom。$ html

foreach ($html->find('a') as $myText)
{
      echo '-----PPPP---->>>>'.$myText->plaintext.'this is test<br/>';   
}

但它正在打印文本和图像。我只需要文本

4 个答案:

答案 0 :(得分:1)

->find('a')->plaintext;

应该这样做

答案 1 :(得分:0)

我没有使用Simple HTML DOM Parser,而是使用了DomDocument

$html = <<<HTML
<a><img src=""/>some text here...</a>
<a><img scr=""/>some text here...</a>
HTML;

$dom = new DomDocument();
$dom->loadHTML($html);
$links = $dom->getElementsByTagName("a");
foreach ($links as $link) {
    var_dump($link->textContent);
}

结果:

string 'some text here...' (length=17)
string 'some text here...' (length=17)

答案 2 :(得分:0)

如何将其分成两部分并在图像标记后打印:

foreach ($html->find('a') as $myText)
{
   $parts = explode("/>", $myText);
   echo $parts[1];
}

答案 3 :(得分:0)

我认为你应该在PHP中使用DOMDocument。

像这样:

$dom = new DOMDocument();
$dom->load($htmlfile);
$atags = $dom->getElementsByTagName('a');
foreach ($atags as $atag) {
    echo $atag->textContent;
}
相关问题