• how to use php to write your xml for you category: development | date: 2010-04-16 12:46:23 | views: 3492

    If you ever have had to write an XML file for an image gallery, and you have done this for galleries with a large number of images, you know how big of a pain in the ass it can be to do by hand.

    Lets use php to save ourselves a ton of time.

    Using an "echo" statement in php with a "for" loop is all you need to do to generate an XML file for as many images as you want. Lets start by setting up your file.

    Say your XML goes like this:

    <img photo="gallery/1.jpg" thumb="gallery/thumbs/1.jpg"/>

    To generate this in PHP you would use the following code:

    $number_of_images = 11;

    $number_of_images = 11;
     
    for($i=1;$i<=$number_of_images;$i++){
    echo '<img photo="gallery/'.$i.'.jpg" thumb="gallery/thumbs/'.$i.'.jpg"/>' . "\n";
    }

    for($i=1;$i<=$number_of_images;$i++){
    echo '<img photo="gallery/'.$i.'.jpg" thumb="gallery/thumbs/'.$i.'.jpg"/>' . "\n";
    }

    Essentially, what your doing is, saying that "$i" as a variable starts at "1". Until that variable is equal to the number of images your using, the "$number_of_images" variable, its going to loop through the statement incrementing $i by 1 each time and writing a new line of xml with the current $i variable in the image name place.

    When you run this script in a browser, you will see a blank screen. Hit "View Source" and you will see your XML code, which you can then copy and paste into your desired .XML document.