Search code examples
phpxmldomgetelementsbytagname

If I know there is only gonna be one element with that name (XML(PHP DOM)), how can I select it?


I am trying to add some data received from a form to an XML file which already exists. I am using DOMDocument in PHP for adding the data to the file...

While I am somewhat successful in adding the data, it is adding into the wrong element.

Now I know there is only gonna be one element with a certain name, which will be the root element. I also know that there is gonna be only one element with a name which will contain other data.

Those elements don't have an ID and I want to read them by getElementsByTagName in PHP using DOMDocument.

So if i know that there is gonna be only one element with that name in the whole file, then can i do something like this:

$element = $dom->getElementByTagName('ElementName'); $element[0];

I mean can I select only the first element in the array? And how should I do it? Because the code above doesn't work.


Solution

  • TagName refers to the name of the html or xml tag. If there is only one you should be able to do something like this:

    $element = $dom->getElementByTagName('ElementName')->item(0);
    

    However it sounds like what you are really looking for can be done with xpath:

    $xpath = new DOMXPath($dom);
    $elements = $xpath->query("//*[@name='ElementName']");
    
    foreach ($elements as $node)
    {
        $element[] = $node;
    }
    

    Now $element[0] should be the element you are looking for.