1

I have a html like below:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>ABC</td>
            <td><a data-permission="allow"></a></td>
        </tr>
        <tr>
            <td>B</td>
            <td><a data-permission="allow"></a></td>
        </tr>
        <tr>
            <td>C</td>
            <td><a data-permission="allow"></a></td>
        </tr>
        <tr>
            <td>D</td>
            <td><a data-permission="allow"></a></td>
        </tr>
        <tr>
            <td>E</td>
            <td><button type="button" data-permission="allow"></button></td>
        </tr>
    </tbody>
</table>

Now i am finding the nodes who contains "data-permission" attributes like (a, button etc.) from above example.
TO do that i am using the below code. Now what i am trying do is remove that whole <a>..</a> or <button>...</button> or any other element if they contain "data-permission" attribute and after deletion only return remaining HTML. So how to achieve that?

$dom = new DOMDocument;
$dom->loadHTML($output);

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//@data-permission-id');
foreach ($nodes as $node) {
    echo $node->nodeValue;
    //$node->parentNode->removeChild($node); throws the error "Not Found Error"
}

Note- I have tried $node->parentNode->removeChild($node); inside loop, but it throws the error. Also after delete that tag, i want to get remaining HTML. I have read the How to delete element with DOMDocument? but it doesn't help.

DS9
  • 2,995
  • 4
  • 52
  • 102
  • you want to remove or only tag, I can do this by jQuery – GYaN Oct 24 '17 at 10:48
  • 2
    Possible duplicate of [How to delete element with DOMDocument?](https://stackoverflow.com/questions/15272726/how-to-delete-element-with-domdocument) – Michel Oct 24 '17 at 10:51
  • with PHP, on server side. @Michel, i have tried that by using $node->parentNode->removeChild($node); but it throws the 'Not Found Error'. – DS9 Oct 24 '17 at 10:55
  • Also, after delete, i am trying to get remaining HTML and i don't know how that's possible. – DS9 Oct 24 '17 at 10:56
  • i think the question is not duplicate, as its has diff. requirement compare to https://stackoverflow.com/questions/15272726/how-to-delete-element-with-domdocument – DS9 Oct 24 '17 at 12:40

1 Answers1

1

Replace your node value to remove : $node->nodeValue = "";

$dom = new DOMDocument;
$dom->loadHTML($output);
echo "Previous : ".PHP_EOL.$dom->textContent.PHP_EOL;
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//*[@data-permission='allow']");
foreach ($nodes as $node) {
    $node->nodeValue = "";
    $dom->saveHTML();
}

Live demo : https://eval.in/885719

Live demo with your table data : https://eval.in/885780

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109