php - 从 PHP 中的 DOMElement 获取特定的子标签

标签 php xml dom

我正在遍历一个 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;
}

打印 label="Full Name:"

关于php - 从 PHP 中的 DOMElement 获取特定的子标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3816806/

相关文章:

php - 双方括号内任何内容的正则表达式

php - 自动页面刷新,无需重新加载整个页面

dom - Durandal:手动从 DOM 中删除 View

php - 检测重复值

php - 使用PHP的Elasticsearch多个术语搜索Json Query构建器

php - 将变量传递给 XSLT

xml - 如何在 REST 中传递复杂的查询?

c# - Xelement - 获取元素

javascript - Uncaught Error : DOM element with id x in Element cache is not same as element in DOM

javascript - 如何遍历 DOM 以确定最大嵌套深度?