Home > Software design >  PHP str_ireplace does not remove content from DomDocument tags
PHP str_ireplace does not remove content from DomDocument tags

Time:06-09

I am trying to remove all content from the td tag having the class attribute by serving as stripos to check if the td indeed has the class attribute and from str_ireplace to replace this navigation-only CSS content class (<td > ... </td>) with empty double quotes as you can see in my Code below:

libxml_use_internal_errors(true);
$doc = new DOMDocument();

$doc->loadHTMLFile("https://website.ndd");

$getTableTags = $doc->getElementsByTagName("table");
$getTdTags = $doc->getElementsByTagName("td");
foreach ($getTableTags as $getTableTag) {
    if (stripos($getTableTag->getAttribute('class'), "infotec") !== false) {
        foreach ($getTdTags as $getTdTag) {
            if (stripos($getTdTag->getAttribute('class'), "navigation-only") !== false) {
                // var_dump($getTableTag);
                // $completeInfoxbox = $doc->saveHTML($getTableTag);
                $getInfoboxPatch1 = str_ireplace($getTdTag, "", $getTableTag);
                echo $doc->saveHTML($getInfoboxPatch1);
            }
        }
    }
}

I get a 100% blank Page yet I did an: echo $doc->saveHTML($getInfoboxPatch1).

So, how can I correct my code so as to REMOVE all the <td> HTML tags having the class attribute whose content of this class attribute is navigation-only: <td > ... </td> ???

Please help me please.

CodePudding user response:

$getInfoboxPatch1 = str_ireplace($getTdTag, "", $getTableTag);
// throws error: str_ireplace(): Argument #1 ($search) must be of type array|string, DOMElement given

str_ireplace takes strings or arrays as search and object parameters. You're passing PHP DOMElements.

To change a PHP DOMDocument element you need to remove the existing element, create a new one, and append it to the old element's parent.

In this case you are removing a text node, creating a new text node, and appending the new text node to the TD tag:

if (stripos($getTdTag->getAttribute('class'), "navigation-only") !== false) {

  // remove child nodes
  while ( $getTdTag->hasChildNodes() ) {
    $getTdTag->removeChild($getTdTag->firstChild);
  }

  // create empty text node
  $emptyTextNode = $doc->createTextNode("");

  // append to TD tag
  $getTdTag->appendChild($emptyTextNode);

  //show updated tag
  echo $doc->saveHTML($getTdTag);

}
  • Related