Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Get children of an XML node with unknown structure

I'm trying to modify an XML document which contains some node that I can identify by name. For example, I might want to modify the <abc>some text</abc> node in a document (which I can identify by the tag name abc)

The problem I'm facing currently is that I don't know the exact structure of this document. I don't know what the root element is called and I don't know which children might contain this <abc> node.

I tried using SimpleXML<...> but this does not allow me to read arbitrary element children:

$xml = new SimpleXMLElement($xmlString);

foreach ($xml->children() as $child) {
    // code here doesnt execute
}

I'm considering building my own XML parser which would have this simple functionality, but I cannot believe that simply iterating over all child nodes of a node (eventually recursively) is not something that is supported by PHP. Hopefully someone can tell me what I'm missing. Thanks!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use DOMDocument

$dom = new DOMDocument();
@$dom->loadXML($xmlString);     

foreach($dom->getElementsByTagName('item') as $item) { 

    if ($item->hasChildNodes()) {

        foreach($item->childNodes as $i) {

            YOUR CODE HERE
        }

    }
}
over 4 years ago · Santiago Trujillo Report

0

I found the solution moments after posting, after being stuck on it for a while..

SimpleXML<...> does not have these features, but the DOMDocument and associated classes do;

$dom = new DOMDocument();
$dom->loadXml($xmlString);

foreach($dom->childNodes as $child) {
    if ($child->nodeName == "abc") {
        $child->textContent = "modified text content";
    }
}

Documentation for future reference, here: http://php.net/manual/en/book.dom.php

Thanks for your help.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!