title: Generate JSON string of Magento's categories and children categories from PHP
body: <p>I'm trying to generate a JSON string that includes the id and url for all my categories, subcategories, and sub-subcategories. The code below only gets me as far as the top-level category, but I also need the second and third as well. My goal is to create a dynamically updating sitemap that decodes the string and makes an unordered list of every category level. </p>
  
  <pre><code>public function createCategoryTree() {
  $_categories = Mage::getModel('catalog/category')-&gt;getCollection()-&gt;addAttributeToSelect('*')-&gt;addIsActiveFilter()-&gt;addLevelFilter(2)-&gt;addOrderField('position'); // load all categories
  $arr = array();
  if ($_categories){ // if there are categories
    foreach ($_categories as $cat){
      $cat_name = $cat-&gt;getName(); // name as key
      if (strlen(stristr($cat_name,'default')) &lt; 3) {
        $cat_id = $cat-&gt;getId(); // id
        $cat_url = $cat-&gt;getUrl(); // url
        $arr[$cat_id] = array('title'=&gt;$cat_name,'url'=&gt;$cat_url); 
      }
    }
  }
  print_r (json_encode($arr));
  die;
  }
  </code></pre>
  
  <p>I get something like this:</p>
  
  <pre><code>{
      "637": {
          "title": "bikes",
          "url": "http:www.123.com/shop/bicycles "
      }
  }
  </code></pre>
  
  <p>But I want something like this:</p>
  
  <pre><code>{
      "637": {
          "title": "bikes",
          "url": "http:www.123.com/shop/bicycles",
          "children": {
              "658": {
                  "title":"wheels",
                  "url":"http:www.123.com/shop/bicycles/wheels"
              },
              "489": {
                  "title": "pumps",
                  "url":"http:www.123.com/shop/bicycles/pumps"
              }
      }
  }
  </code></pre>
  
  <p>Appreciate your time and help!</p>