【问题标题】:php DOMdocument how to select multiple tag elements?php DOMdocument如何选择多个标签元素?
【发布时间】:2022-01-27 02:46:01
【问题描述】:

我有下面的代码

  $Dom = new DOMDocument;
  @$Dom->loadHTML("<?xml version='1.0' encoding='UTF-8'?><body>$body</body>");
  $links = $Dom->getElementsByTagName('a');
  $arr = array();
  foreach ($links as $link) {
    if ($link->attributes[0]->name == 'href' && $link->attributes[0]->value != '#') {
      $link->attributes[0]->value = 'changed.com';
    }
  }

我还想添加类似$Dom-&gt;getElementsByTagName('a,button');的按钮标签

【问题讨论】:

  • 你不能那样做。它不像 CSS 选择器,你不能同时选择多个东西。
  • 再做一个选择:$buttons = ...

标签: php


【解决方案1】:

您可以使用DOMXPath::query() 或扩展DOMElement 并通过DOMDocument::registerNodeClass() 注册

【讨论】:

    【解决方案2】:

    您可以通过 XPath 使用多重选择器:$xpath-&gt;query('//a | //button')

    // HTML sample 
    $body = '<p><a href="#">link</a><a href="#">another</a><button>button</button><i>some text</i></p>';
    
    // Load and query
    $dom = new DOMDocument;
    @$dom->loadHTML("<?xml version='1.0' encoding='UTF-8'?><body>$body</body>");
    $xpath = new DOMXPath($dom);
    $nodelist = $xpath->query('//a | //button');
    
    // Display information
    echo "Length is : " . $nodelist->length, PHP_EOL;
    foreach ($nodelist as $index => $node) {
        echo "- Node $index is $node->nodeName" . PHP_EOL;
    }
    

    输出:

    Length is : 3
    Node 0 is a
    Node 1 is a
    Node 2 is button
    

    另见live demo (3v4l.org)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2022-08-12
      • 2015-12-15
      相关资源
      最近更新 更多