Need help with file opening

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • freddukes
    New Member
    • Sep 2008
    • 18

    Need help with file opening

    Okay... I'm a PHP noob but I have a good background in C++ and Python... Now all I want to do is iterate through the following file, and appending all products to an array, with information stored inside the array for each product, then return it... here is the file:

    Code:
    // ../docs/products.txt
    
    // This document is for displaying all your products
    // To do this, there is a special format to create each offer.
    // The format is as follows:
    // [Unique Product ID]
    // name=<name>
    // description=<description>
    // price=<price as pounds.pence e.g. 19.99 is £19.99>
    // image=<image directory from ../images/products>
    // extras=special or popular... If it's both then display it via a comma... special,popular... This is only if the product is either a special or a popular product. If it doesn't have any, put none
    
    [1]
    name=Green Laser Pen
    description=This pointer is significantly brighter (about 50 times) than a red laser pointer and because of its unusual color it is much more noticeable. I mean come on, a 532 nm green laser wavelength is obviously superior to a laughable 650 nm red laser wavelength....
    price=39.99
    image=1.jpg
    extras=special,popular
    
    [2]
    name=Cheese
    description=A cheesy gadget
    price=13.37
    image=cheese.jpg
    extras=none
    Here is the function

    [PHP]
    <?PHP
    function getAllProductDe tails()
    {
    $arrayDetails;
    $contents = file("docs/products.txt");
    $productNum = 0;
    foreach ($contents as $line_number => $theData)
    {
    if (str_replace(" ", "", $theData) && !substr($theDat a, 0, 2) == "//")
    {
    if (ereg ("[[][0-9]*[]]", $theData))
    {
    $productNum = (int)str_replac e("]", "", str_replace("[", "", $theData) );
    $arrayDetails[$productNum];
    }
    else if ($productNum)
    {
    $equalPos = strpos($theData , "=");
    $arrayDetails[$productNum][substr($theData , 0, equalPos)] = substr($theData , equalPos + 1);
    }
    }
    }
    return $arrayDetails;
    }

    function getAllExtras( $extra )
    {
    $arrayList = getAllProductDe tails();
    $theArray;
    if ($arrayList)
    {
    foreach ($arrayList as $key => $value)
    {
    if (strstr($value["extras"], $extra))
    {
    $theArray[$key] = $value;
    }
    }
    return $theArray;
    }
    else
    {
    echo "Crap";
    $theArray["name"] = "NULL";
    $theArray["image"] = "1.jpg";
    $theArray["descriptio n"] = "NULL DESCRIPTION";
    $theArray["price"] = "13.37";
    return $theArray;
    }
    }
    ?>
    [/PHP]

    Here is the code that calls that function

    [PHP]
    <?php
    $arrayList = getAllExtras( "special" );
    $randPos = array_rand($arr ayList);
    $randomSpecial = $arrayList[$randPos];
    echo "<div class='picture' >";
    echo "<img src=images/products/".$randomSpecia l['image']." />;";
    echo "</div>";

    echo "<div class='text'>";
    echo "<h1>".$randomS pecial["name"]."</h1>";
    echo "<p>".$randomSp ecial["descriptio n"]."</a>";
    echo "<p>".$randomSp ecial["price"]."</p>";
    echo "</div>";
    ?>
    [/PHP]

    The end product ends up like this which doesn't look right :( Please help me if you can...

    Oh yeah, I did manage to get this working in python with the following code:

    Code:
    def getAllProductDetails():
        arrayDetails = {}
        f = open("D:/College Work/college/unit 21/website/docs/products.txt", "r")
        l = f.readlines()
        f.close()
        l = ''.join(map(lambda x: x.replace('\r','\n'), l)).split('\n')
        productNumber = 0
        p = re.compile('[[][0-9]*[]]')
        for line in l:
            if line.replace(' ','') and not line.startswith('//'):
                m = p.match(line)
                if m:
                    product = int(line.replace('[','').replace(']',''))
                    arrayDetails[product] = {}
                else:
                    eqPos = line.find('=')
                    if eqPos:
                        arrayDetails[product][line[:eqPos]] = line[eqPos + 1:]
        return arrayDetails
    I tried to create the equivalent of my PHP code in python, and it worked.. I'm lost, I've been at this for hours... I thank you in advance

    -freddukes
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    hm, your regex looks a bit strange (at least to me). I would use something like:

    preg_match("@\[([0-9]+)\]@", $theData, $prodNum)
    // $prodNum[1] is your product number

    note: preg_match() is usually described as faster than ereg() and you may use a different delimiter than I (I like @ as delimiter, since it hardly occurs in my files)

    regards

    Comment

    • freddukes
      New Member
      • Sep 2008
      • 18

      #3
      Thank you so much for the reply... I managed to get round to it and I fixed that along with a few other errors and it now works perfect. Thank you so much for the help!

      -freddukes

      Comment

      Working...