PHPology.co.uk Collective of freelance web developers and designers

  • PHP Simple_XML with namespaces

    Had to read in an external RSS file from T3 and needed to drill into the "content" node which had a namespace. Using traditional ways of echoing out this node was not working so searching the net found a nice simple solution.

    Below is the code to loop thru the "items" node without the name namespace involved:
    <?php
    $url = "http://best-apps.t3.com/category/platforms/android/feed/";

    //download the feed from t3 with fopen
    $handle = fopen($url, "r");
    while (!feof($handle)) {
      $contents .= fread($handle, 8192);
    }
    fclose($handle);
    //echo $contents;

    $xml = simplexml_load_string($contents);
    //print_r($xml);

    echo "<ul>";
    $i = 0;
    foreach($xml->channel->item as $item)
    {
    $alt_bg = (fmod($i, 2)) ? "bg-alt-even" : "bg-alt-odd"; //alternative background colour thing
    ?>
      <li class="<?php echo $alt_bg?>">
       <a href="<?php echo $item->link?>" target="_blank"><?php echo $item->title?></a>
      </li>
     <?php
     $i++;
    }
    echo "</ul>";
    ?>

    Below code includes the way I drilled into the namespace for "content:encoded"
    <?php
    $url = "http://best-apps.t3.com/category/platforms/android/feed/";

    //download the feed from t3 with fopen
    $handle = fopen($url, "r");
    while (!feof($handle)) {
      $contents .= fread($handle, 8192);
    }
    fclose($handle);
    //echo $contents;

    $xml = simplexml_load_string($contents);
    //print_r($xml);

    echo "<ul>";
    $i = 0;
    foreach($xml->channel->item as $item)
    {
     $alt_bg = (fmod($i, 2)) ? "bg-alt-even" : "bg-alt-odd"; //alternative background colour thing

     //Use that namespace from "content"
      $namespaces = $item->getNameSpaces(true);
      $content = $item->children($namespaces['content']);
      echo $content->encoded;
     ?>
      <li class="<?php echo $alt_bg?>">
       <a href="<?php echo $item->link?>" target="_blank"><?php echo $item->title?></a>
      </li>
     <?php
     $i++;
    }
    echo "</ul>";
    ?>

    The code reference is just a mock up and will need cleaning up but gives you an idea at least.

  • Comments

    0 comment(s)

    Be the first to comment!

    Add your comment
    Name*:
    Email*:
    Website URL (including full path e.g. http://www.yourwebsite.com/):
    Comment* (html/script tags will be removed):
    What do you see below?: