簡體   English   中英

從PHP中的DOMElement獲取特定的子標記

[英]Get a specific child tag from a DOMElement in PHP

我正在瀏覽xml定義文件,我有一個DOMNodeList,我正在瀏覽。 我需要提取可能在當前實體中或可能不在當前實體中的子標記的內容

<input id="name">
  <label>Full Name:</label>
  <required />
</input>
<input id="phone">
  <required />
</input>
<input id="email" />

我需要更換????????????? 有一些東西,如果它存在,我會得到標簽標簽的內容。

碼:

foreach($dom->getElementsByTagName('required') as $required){
  $curr = $required->parentNode;

  $label[$curr->getAttribute('id')] = ?????????????
}

預期結果:

Array(
  ['name'] => "Full Name:"
  ['phone'] => 
)

奇怪的是:你已經知道了答案,因為你已經在腳本中使用了它, getElementsByTagName()
但這次不是將DOMDocument作為上下文“節點”而是使用input DOMElement:

<?php
$doc = getDoc();
foreach( $doc->getElementsByTagName('required') as $e ) {
  $e = $e->parentNode; // this should be the <input> element
  // all <label> elements that are direct children of this <input> element
  foreach( $e->getElementsByTagName('label') as $l ) {
    echo 'label="', $l->nodeValue, "\"\n";
  }
}

function getDoc() {
  $doc = new DOMDocument;
  $doc->loadxml('<foo>
    <input id="name">
      <label>Full Name:</label>
      <required />
    </input>
    <input id="phone">
      <required />
    </input>
    <input id="email" />
  </foo>');
  return $doc;
}

prints label="Full Name:"

暫無
暫無

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

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