Question

I'm trying to get the names of certain elements in order to a populate a combo list, all the example I can find use the simpleXML lib which I do not have access to.

The current xml schema:

<alist>
  <a>
      <a1>text a</a1>
      <a2>text a</a2>
  </a>
  <b>
      <b1>text b</b1>
      <b2>text b</b2>
  </b>
</alist>

and the current PHP code:

$xmlFile = "file.xml";
$dom = DOMDocument::load($xmlFile);

What I want to do is get the name of the child elements of 'alist' (currently it would be a and b).

Was it helpful?

Solution 2

It's a property on DOMElement called tagName. E.g.:

<?php

$xml = <<<XML
<alist>
  <a>
      <a1>text a</a1>
      <a2>text a</a2>
  </a>
  <b>
      <b1>text b</b1>
      <b2>text b</b2>
  </b>
</alist>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$alist = $dom->getElementsByTagName('alist')->item(0);

foreach($alist->childNodes as $child) {
    if ($child->nodeType === XML_ELEMENT_NODE) var_dump($child->tagName);
}

OTHER TIPS

Be careful with tagName, it will contain a namespace prefix if the element has one. localName will be the name without a namespace prefix.

Xpath allows you to fetch and iterate the child element nodes directly:

$xml = <<<XML
<alist>
  <a>
      <a1>text a</a1>
      <a2>text a</a2>
  </a>
  <b>
      <b1>text b</b1>
      <b2>text b</b2>
  </b>
  <foo:c xmlns:foo="bar"/>
</alist>
XML;

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);

foreach($xpath->evaluate('/alist/*') as $child) {
  var_dump($child->localName);
}

Output: https://eval.in/149684

string(1) "a"
string(1) "b"
string(1) "c"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top