473,322 Members | 1,566 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

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:

Expand|Select|Wrap|Line Numbers
  1. // ../docs/products.txt
  2.  
  3. // This document is for displaying all your products
  4. // To do this, there is a special format to create each offer.
  5. // The format is as follows:
  6. // [Unique Product ID]
  7. // name=<name>
  8. // description=<description>
  9. // price=<price as pounds.pence e.g. 19.99 is £19.99>
  10. // image=<image directory from ../images/products>
  11. // 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
  12.  
  13. [1]
  14. name=Green Laser Pen
  15. 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....
  16. price=39.99
  17. image=1.jpg
  18. extras=special,popular
  19.  
  20. [2]
  21. name=Cheese
  22. description=A cheesy gadget
  23. price=13.37
  24. image=cheese.jpg
  25. extras=none
  26.  
Here is the function

[PHP]
<?PHP
function getAllProductDetails()
{
$arrayDetails;
$contents = file("docs/products.txt");
$productNum = 0;
foreach ($contents as $line_number => $theData)
{
if (str_replace(" ", "", $theData) && !substr($theData, 0, 2) == "//")
{
if (ereg ("[[][0-9]*[]]", $theData))
{
$productNum = (int)str_replace("]", "", 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 = getAllProductDetails();
$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["description"] = "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($arrayList);
$randomSpecial = $arrayList[$randPos];
echo "<div class='picture'>";
echo "<img src=images/products/".$randomSpecial['image']." />;";
echo "</div>";

echo "<div class='text'>";
echo "<h1>".$randomSpecial["name"]."</h1>";
echo "<p>".$randomSpecial["description"]."</a>";
echo "<p>".$randomSpecial["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:

Expand|Select|Wrap|Line Numbers
  1. def getAllProductDetails():
  2.     arrayDetails = {}
  3.     f = open("D:/College Work/college/unit 21/website/docs/products.txt", "r")
  4.     l = f.readlines()
  5.     f.close()
  6.     l = ''.join(map(lambda x: x.replace('\r','\n'), l)).split('\n')
  7.     productNumber = 0
  8.     p = re.compile('[[][0-9]*[]]')
  9.     for line in l:
  10.         if line.replace(' ','') and not line.startswith('//'):
  11.             m = p.match(line)
  12.             if m:
  13.                 product = int(line.replace('[','').replace(']',''))
  14.                 arrayDetails[product] = {}
  15.             else:
  16.                 eqPos = line.find('=')
  17.                 if eqPos:
  18.                     arrayDetails[product][line[:eqPos]] = line[eqPos + 1:]
  19.     return arrayDetails
  20.  
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
Sep 21 '08 #1
2 1431
Dormilich
8,658 Expert Mod 8TB
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
Sep 22 '08 #2
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
Sep 24 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: John Morgan | last post by:
I am using the following link to download a file of about 50k <a target= "_blank" href="http://www.bsecs.org.uk/ExecDocs/documentStore/elfridaWord.doc">open file</a> If I save the file to...
0
by: Norm Wong | last post by:
If anyone is interested in using db2uext2 with Cygwin gcc compiler on Windows, I've modified the IBM provided sample with the attached file. There are two main modifications. The mkdir command...
5
by: zambak | last post by:
Hi I have assignment for some wierd compression alghoritam that will read in from a file convert characters to 5 bit codes and then write out compressed version of the original file. For...
7
by: pillip | last post by:
I am trying to use fopen and fget to input two files and then output them into one file. Each input file has two columns and 20 rows, however since the first column in each input file is same (...
6
by: Can | last post by:
I am trying to create a .dll file using VB.Net Standard using the info from this website http://www.devcity.net/Articles/111/1/vbnet_se_dll.aspx My problem is when I open up the .vbproj file in...
0
by: jonathandrott | last post by:
here is my code for a btn click event. i want to insert fields from one access db to another. look for ->>>>>>> below. can some help me with this syntax? am i opening the db's correctly? ...
2
by: Craig | last post by:
Hi there, I'm trying to open colour BMPs using PIL and I'm getting the following errors. Opening a 16 colour BMP I get: Traceback (most recent call last): File "<pyshell#3>", line 1, in...
8
by: rn5a | last post by:
I have a HTML page named Index.html which is divided into 3 frames. The URL of 2 of the frames are HTML pages but the 3rd frame houses a ASP page. Now when I go to Windows Explorer, navigate to...
3
by: =?iso-8859-9?B?RGlu52F5IEFr5/ZyZW4=?= | last post by:
When I execute the following code #include <stdio.h> #include <stdlib.h> int main(void) { FILE *bmp; bmp = fopen("deneme.bmp","w"); fputc(10,bmp);
4
by: Uriel88 | last post by:
Hello, I am working with developing an application that uses the Netmon 3.2 API. Currently they have a PInvoke wrapper to access unmanaged C++ DLL functions. Basically what I am attempting to do...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.