簡體   English   中英

php DOMdocument如何select多個標簽元素?

[英]php DOMdocument how to select multiple tag elements?

我在下面有以下代碼

  $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->getElementsByTagName('a,button');

您可以使用DOMXPath::query()或擴展DOMElement並通過DOMDocument::registerNodeClass()

您可以使用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

另見現場演示 (3v4l.org)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM