Symfony 2 Dom Crawler: how to get only text() in Element

六月ゝ 毕业季﹏ 提交于 2019-12-10 12:58:40

问题


Using Dom Crawler to get only text (without tag).

$html = EOT<<<
  <div class="coucu">
    Get Description <span>Coucu</span>
  </div>
EOT;

$crawler = new Crawler($html);
$crawler = $crawler->filter('.coucu')->first()->text();

output: Get Description Coucu

I want to output (only): Get Description

UPDATE:

I found a solution for this: (but it's really bad solution)

...
$html = $crawler->filter('.coucu')->html();
// use strip_tags_content in https://php.net/strip_tags
$html = strip_tags_content($html,'span');

回答1:


Ran into the same situation. I ended up going with:

$html = $crawler->filter('.coucu')->html();
$html = explode("<span", $html);
echo trim($html[0]);



回答2:


Based on the criteria within your question, I think you would be best served by modifying your CSS Selector to: $crawler = $crawler->filter('div.coucu > span')

From there you can go $span_text = $crawler->text();

or to simplify things: $text = $crawler->filter('div.coucu > span')->text();

The text() method returns the value of the first item within the list.




回答3:


function extractCurrentText(Crawler $crawler)
{
  $clone = new Crawler();
  $clone->addHTMLContent("<body><div>" . $crawler->html() . "</div></body>", "UTF-8");
  $clone->filter("div")->children()->each(function(Crawler $child) {
    $node = $child->getNode(0);
    $node->parentNode->removeChild($node);
  });
  return $clone->text();
}



回答4:


The HTML-removing solution it's based on regexes to strip HTML away (bad idea Using regular expressions to parse HTML: why not?), and the explode solution is limited.

I came up going by difference: get all the text, then remove the non-own text with str_replace.




回答5:


This works nicely without hacky workarounds:

$crawler->filter('.coucu')->children()->each(function (Crawler $crawler) {
    $crawler->getNode(0)->parentNode->removeChild($crawler->getNode(0));
});
$crawler->text(); // Get Description


来源:https://stackoverflow.com/questions/30116485/symfony-2-dom-crawler-how-to-get-only-text-in-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!