php DOMdocument how to select multiple tag elements?

82
January 28, 2022, at 04:50 AM

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

Answer 1

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

Answer 2

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).

READ ALSO
Compile node module with node-gyp for a specific NODE_MODULE_VERSION

Compile node module with node-gyp for a specific NODE_MODULE_VERSION

I am trying to use an npm package fsuipc in an electron appHowever, when I start the app I get the following error

120
Replacement of com.android.build.api.transform.Transform classes

Replacement of com.android.build.api.transform.Transform classes

I could see in the android document that Transform classes are deprecated but I could not see the new API which we should use instead of Transform classes

113
How to select an entry from a MySQL database by searching for a case-sensitive username

How to select an entry from a MySQL database by searching for a case-sensitive username

I have set up a MySQL database and created a login table using MySQL WorkbenchI am using a MySQL 8

90
Content/map is undefined

Content/map is undefined

Let's say I have this:

86