简体   繁体   中英

php DOMdocument how to select multiple tag elements?

I have the following code below

  $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';
    }
  }

i want to also add the button tag something like this $Dom->getElementsByTagName('a,button');

You can use DOMXPath::query() or extends DOMElement and register by DOMDocument::registerNodeClass()

You can use a multiple selector using XPath : $xpath->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;
}

Output:

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

See also a live demo (3v4l.org) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM