从PHP中的DOMElement获取特定的子标记

Tys*_*est 6 php xml dom

我正在浏览xml定义文件,我有一个DOMNodeList,我正在浏览.我需要提取可能在当前实体中或可能不在当前实体中的子标记的内容

<input id="name">
  <label>Full Name:</label>
  <required />
</input>
<input id="phone">
  <required />
</input>
<input id="email" />
Run Code Online (Sandbox Code Playgroud)

我需要更换????????????? 有一些东西,如果它存在,我会得到标签标签的内容.

码:

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

  $label[$curr->getAttribute('id')] = ?????????????
}
Run Code Online (Sandbox Code Playgroud)

预期结果:

Array(
  ['name'] => "Full Name:"
  ['phone'] => 
)
Run Code Online (Sandbox Code Playgroud)

Vol*_*erK 8

奇怪的是:你已经知道了答案,因为你已经在脚本中使用了它,getElementsByTagName().
但这次不是将DOMDocument作为上下文"节点"而是使用inputDOMElement:

<?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;
}
Run Code Online (Sandbox Code Playgroud)

版画 label="Full Name:"