Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7037717
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T01:34:44+00:00 2026-05-28T01:34:44+00:00

Specifically, I want to convert the XML structure into this format for the database

  • 0

Specifically, I want to convert the XML structure into this format for the database so that I can use modified preorder tree traversal:

database structure
(source: sitepointstatic.com)

My XML structure looks something like this:

<?xml version="1.0" standalone="yes"?>
<products>
    <node>
      <name>Top Membership</name>
      <node>
        <name>Middle Membership</name>
        <node>
          <name>Bottom Membership</name>
          <node>
            <name>Some content</name>
            <node>
              <name>Specific content</name>
            </node>
          </node>
        </node>
      </node>
    </node>

I’ve made a PHP script to traverse the XML structure and dump me out the names, I’m just having trouble working out the left and right values. I think I probably have to change my traversal logic so that it’s followed down to a single leaf each time, then goes back up and starts again, rather than bottoming each entire branch each time. If I could do this then I think it would be easier to calculate left and right.

My PHP script so far:

<?php

$node = new SimpleXMLElement(file_get_contents('products.xml'));

echo '<pre>';

function getRowData($node, $depth)
{  
  //Not a leaf
  if(isset($node->node))
  {
    echo $node->name."\t\t\t($depth) parent, children: ".count($node->children())."\n";

    foreach($node->node as $n)
      getRowData($n, $depth + 1);
  }
  else //It's a leaf
    echo $node->name."\t\t\t($depth) leaf\n";


}

getRowData($node->node, 1);

echo '</pre>';

?>

I’m using this SitePoint article for reference http://www.sitepoint.com/hierarchical-data-database-2/

Edit:

Revised PHP script which is closer to a solution (and outputs in a better format with more (possibly relevant) numbers):

<?php

$node = new SimpleXMLElement(file_get_contents('products.xml'));

echo '<table border="1">';
  echo '
    <tr>
      <th>Name</th>
      <th>Depth</th>
      <th>Child num</th>
      <th>Children</th>
      <th>Ancestors</th>
      <th>Total siblings</th>
      <th>"Left"</th>
      <th>Parent "Left"</th>
    </tr>';

function getRowData($node, $depth = 1, $child_num = 1, $prior_nodes = 0, $sibling_total = 0, $parent_left = 0)
{  

    echo '<tr>';
  echo '
          <td>'.$node->name."</td>
          <td>$depth</td>
          <td>$child_num</td>
          <td>".(count($node->children()) - 1)."</td>
          <td>$prior_nodes</td>
          <td>$sibling_total</td>";

  $left = $parent_left + ($child_num == 1 ? 1 : ($child_num * 2) - 1);


          echo "<td>$left</td>";
          echo "<td>$parent_left</td>";
  echo '</tr>';
  $child_num = 1;

  foreach($node->node as $n)
  {
    getRowData(
            $n, 
            $depth + 1, 
            $child_num++, 
            $prior_nodes + (count($node->children()) - 1), 
            (count($node->children()) - 1),
            $left
    );
  }
}

getRowData($node->node);

echo '</table>';

?>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T01:34:44+00:00Added an answer on May 28, 2026 at 1:34 am

    The general approach here is to create an adjacency list (a tree), then
    traverse the tree assigning lft on your way down and rgt on your way up.

    Assuming this xml:

    <?xml version="1.0" standalone="yes"?>
    <products>
    <node><name>Top Membership</name>
      <node><name>Middle Membership</name>
        <node><name>Bottom Membership 1</name></node>
        <node><name>Bottom Membership 2</name>
          <node><name>Some content</name>
            <node><name>Specific content</name></node>
          </node>
        </node>
      </node>
    </node>
    </products>
    

    The following code should do what you need.

    $root = simplexml_load_string($xml);
    
    function nested_set($parent, $rows=array(), $counter=1) {
        foreach ($parent->node as $node) {
            $row = array(
                'title'   => (string) $node->name,
                'parent' => (string) $parent->name,
                'lft'    => $counter++,
                'rgt'    => null,
            );
            list($rows, $counter) = nested_set($node, $rows, $counter);
            $row['rgt'] = $counter++;
            $rows[] = $row;
        }
        return array($rows, $counter);
    }
    
    function print_rows($rows) {
        $sep = '+'.str_repeat('-', 22).'+'.str_repeat('-', 22).'+'.str_repeat('-', 5).'+'.str_repeat('-', 5).'+'."\n";
        echo $sep;
        echo vsprintf("| %-20s | %-20s | %3s | %3s |\n", array_keys($rows[0]));
        echo $sep;
        foreach ($rows as $row) {
            echo vsprintf("| %-20s | %-20s | %3d | %3d |\n", array_values($row));
        }
        echo $sep;
    }
    
    list($rows, $counter) = nested_set($root);
    // rows will be in reverse-traversal order
    print_rows($rows);
    

    Output will be:

    +----------------------+----------------------+-----+-----+
    | title                | parent               | lft | rgt |
    +----------------------+----------------------+-----+-----+
    | Bottom Membership 1  | Middle Membership    |   3 |   4 |
    | Specific content     | Some content         |   7 |   8 |
    | Some content         | Bottom Membership 2  |   6 |   9 |
    | Bottom Membership 2  | Middle Membership    |   5 |  10 |
    | Middle Membership    | Top Membership       |   2 |  11 |
    | Top Membership       |                      |   1 |  12 |
    +----------------------+----------------------+-----+-----+
    

    For more information on nested sets, see Joe Celko’s work:

    • Trees in SQL
    • The chapter on trees and hierarchies in SQL for Smarties (I have the first edition–it’s very valuable.)
    • His book Trees and Hierarchies in SQL for Smarties
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to get into Erlang programming, specifically some yaws stuff. (Currently, I use
We've got a file-based program we want to convert to use a document database,
I'm aware that serializing is used to convert data types into a storable format,
I want to convert an Object into a String in PHP. Specifically, I'm trying
I want to change an audio file format into another. Specifically, I want to
Specifically I want to know what the data structure for the imports (idata) section
I'm trying to write a plugin that will extend InheritedResources . Specifically I want
I want to keep my website/s in version control (Subversion specifically) and use svn
I know some DI frameworks support this (e.g. Ninject ), but I specifically want
I'm trying to do some image file work, specifically convert one image file format

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.