Php - how to remove/delete tag with specific string in QueryPath?

294 Views Asked by At

How to filter the node that has a certain string inside it and Delete or Remove it.

Something like

The XML is like:

<?xml version="1.0"?>
    <user>

        <urls>
          <link>www.weblink-1.com</link>
          <link> www.weblink-2.com</link>
          <link> www.weblink-3.com</link>
          <link> www.weblink-4.com</link>
          <link> www.weblink-5.com</link>
        </urls>

    </user>

Let's say I want to remove/delete <link> www.weblink-4.com</link> using QueryPath how do you achieve that?

I tried something like:

 $r= qp($path,'user')->find("urls>link")->
 filter("link:contains('<link> www.weblink-4.com</link>')");
 print  "<h1>".$r."</h1>";

 ///***ERROR: Catchable fatal error: 
 Object of class QueryPath\DOMQuery could not be converted to string* 

I have also tried something like:

 $r= qp($path,'user')->find("urls>link:contains('<link> www.weblink-4.com</link>')"); 

 print  "<h1>".$r."</h1>";


 ///***ERROR: Catchable fatal error: 
 Object of class QueryPath\DOMQuery could not be converted to string* 

And then something like:

 $qp =  qp($path,'user>urls>link')->filter("link:contains('<link> www.weblink-4.com</link>')")->remove();
$qp->writeXML($path);   

   ///This Deletes the entire Document's nodes leaving only the *<?xml version="1.0"?>* 

This should be simple but turning to be rather very stressful..... Any Suggestion?

2

There are 2 best solutions below

0
Universal Grasp On

To achieve this, QueryPath became kinda stressful. I got some hint from: @Paul Crovella ... And rather I used:

$path = "../ntmhp/prdat/".$userId."/xmls/rf/rss.xml";
            $dom = new DOMDocument();
            $dom->load($path);

            $xpath = new DOMXPath($dom);

            foreach($xpath->query('//link[contains(., "www.weblink-4.com")]') as $node) {
            $node->parentNode->removeChild($node);
            }

            $dom->save($path);

This was fast and effective.

Hope it helps someone.

3
gyaani_guy On

filterPreg works alright for me.

$elements = htmlqp($page, 'user urls linky');
$filtered = $elements->filterPreg("/www.weblinky-[^4].com/");
echo count($filtered ); // 4

Although.. I think it will require looping though the $filtered elements to reconstruct the HTML, which isn't ideal IMO..