Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

xml - Get a specific child tag from a DOMElement in PHP

I am walking through a xml definition file and I have a DOMNodeList that I am walking through. I need to extract the contents of a child tag that may or may not be in the current entity

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

I need to replace ????????????? with something that gets me the contents of the label tag if it exists.

Code:

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

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

Expected Result:

Array(
  ['name'] => "Full Name:"
  ['phone'] => 
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Strange thing is: you already know the answer since you've used it in your script, getElementsByTagName().
But this time not with the DOMDocument as context "node" but with the 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, ""
";
  }
}

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:"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...