re1
re1

Reputation: 457

I want to exclude only the JavaScript tag contents when retrieving only the text of the body element in XPath

I want to exclude only the JavaScript tag contents when retrieving only the text of the body element in XPath

▼index.html

<body>

  I want to acquire only "text excluding HTML tag" included in this part.

  <script language="JavaScript" type="text/javascript">
      var foo = 42;
  </script>

</body>

I have created the following code with DomCrawler. But, because it contains JavaScript tag contents, I could not get the intended results..

<?php

$crawler->filterXPath('//body')->each(function (DomCrawler $node) use ($url) {
    $result = trim($node->text());
});

Upvotes: 0

Views: 472

Answers (2)

delboy1978uk
delboy1978uk

Reputation: 12355

Give this a try:

<?php

$x = '<body>

  I want to acquire only "text excluding HTML tag" included in this part.

  <script language="JavaScript" type="text/javascript">
      var foo = 42;
  </script>

</body>';

$dom = new DOMDocument();
$dom->loadHTML($x);
$script = $dom->getElementsByTagName('script')->item(0);
$script->parentNode->removeChild($script);
$body = $dom->getElementsByTagName('body')->item(0);
echo $body->nodeValue;

Working example HERE https://3v4l.org/n2UQT

Upvotes: 2

Waqas Ahmed
Waqas Ahmed

Reputation: 185

I would like to suggest you use DomXpath in which you can filter the content. by query. I am not pretty sure about Domcrawler.

<?php
// to retrieve selected html data, try these DomXPath examples:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);

// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");

// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/script");

// example 3: same as above with wildcard
$elements = $xpath->query("*/script");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>

Upvotes: 1

Related Questions