【问题标题】:Get a specific child tag from a DOMElement in PHP从 PHP 中的 DOMElement 获取特定的子标签
【发布时间】:2011-04-18 12:35:18
【问题描述】:

我正在浏览一个 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'] => 
)

【问题讨论】:

    标签: php xml dom


    【解决方案1】:

    奇怪的是:你已经知道答案了,因为你已经在你的脚本中使用了它,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:"

    【讨论】:

    • 摇滚,就可以了,谢谢!
    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多