【问题标题】:Php - how to remove/delete tag with specific string in QueryPath?Php - 如何在 QueryPath 中删除/删除带有特定字符串的标签?
【发布时间】:2016-08-25 02:44:12
【问题描述】:

如何过滤其中包含特定字符串的节点以及DeleteRemove

类似

XML 是这样的:

<?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>

假设我想使用QueryPath 删除/删除&lt;link&gt; www.weblink-4.com&lt;/link&gt;,您是如何实现的?

我尝试了类似的方法:

 $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* 

我也尝试过类似的方法:

 $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* 

然后是这样的:

 $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"?>* 

这应该很简单,但变得相当有压力......有什么建议吗?

【问题讨论】:

    标签: php xml nodes querypath


    【解决方案1】:

    为了实现这一点,QueryPath 变得有点压力。我得到了一些提示: @Paul Crovella ... 而我使用的是:

    $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);
    

    这是快速有效的。

    希望对某人有所帮助。

    【讨论】:

      【解决方案2】:

      filterPreg 对我来说没问题。

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

      虽然.. 我认为它需要循环通过 $filtered 元素来重建 HTML,这不是理想的 IMO..

      【讨论】:

      • 谢谢,虽然我收到警告:Warning: preg_match(): Delimiter must not be alphanumeric or backslash in...
      • 我使用的是旧 (2.1) 版本的 QP,所以这可能是造成差异的原因... filterPreg 的不同分隔符,例如 "#www.weblinky-[^4].com# "也可以试试。
      • 我现在面临一个不同的问题...您可以帮忙...请参阅链接::: stackoverflow.com/questions/36957442/…
      猜你喜欢
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 2013-02-24
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多