-2

I am upgrading the way my website runs, I have already integrated mant php scripts in pages, but I am trying to develop fully php based site, eg, instead of loading urls:

url/events/event-1
url/events/event-2

^^^ 2 seperate pages

I am trying to load

url/event?url=event-1

this is so I can update 1 page but load different content depending on the

$_GET['url']

parameter.....

what I have so far...

I load url/event?url=dance

it will automatically search a directory for the filename 'dance.txt'

if the file does not exist, it forwards to main events page (url/events)

if the files does exist, it creates a one line string about the event....

the file content is listed like this:

Dance::::18-02-2012::::http://{external link}::::Event Information

the script I have developed to import this data and display it, works fine, but I need a page that will load all events each in a separate div.......

producing this page is simple enough if I can figure out how to arrange the event array data into a multidimensional array for all events...

for individual events, the script simply defines variables as:

$name, $date, $link, $writeup

I have attached sample code of how I do this...

    $dir    = '/server/htdocs/data/';     // path to dir with all event txt files in
$files = scandir($dir);

$fruit = array_shift($files);

$fruit2 = array_shift($files);    // array shifts remove values of '.' and '..'

$line = implode(" ",$files);    // back into string for str_replace

// echo $line;

$oldword = ".txt";

$newword = "";

$newline = str_replace($oldword, $newword, $line);

// echo $newline;


$files = explode(" ", $newline); // array of filenames

if (in_array($url, $files)) {
  $contents = file_get_contents('data/'.$url.'.txt');
} else { header('Location: http://{url}/events'); }

$info = explode('::::', $contents);

// print_r($info);

$name = $info[0];

$date = $info[1];

$link = $info[2];

$writeup = $info[3];

this works perfectly for individual pages, however, I need to have an array like this:

$events = array ( array ( Name => event-1,
                          Date => date-1,
                          Link => link-1,
                          Writeup => event-info ),

                  array ( Name => event-2,
                          Date => date-2,
                          Link => link-2,
                          Writeup => event-info ),

                  array ( Name => event-3,
                          Date => date-3,
                          Link => link-3,
                          Writeup => event-info )
                        );

this is how I presume the array would be formed, but I need the script to count how many files there are in the /data/ folder, and then (I'm presuming) have a foreach loop so that for each array (event) I can echo:

<div id="content2"> 
                    <div class="post">
<center><h2><u>'.$name.' ('.$date.')</u></h2></center>
                       <p class="postmeta"></p>
                        <div class="entry">

<CENTER><img src="events/posters/'.$name.'.jpg" height="400" width="500"></center>

<p><p>

<p>'.$writeup.'</p>

<p><a href="'.$link.'" " target="_blank">'.$name.' Online</a></p>


 </div>
                    </div><!-- post --> 
                </div><!-- content2 -->

I know it may seem a complicated way of going around things, but this way my site will be 100% editable via data in txt files, as right now I have to clone existing page, then re-write all content in it for new event!

foreach($files as $key => $value) {

$array[] = array(explode('::::',(file_get_contents('data/'.$files[$key].'.txt'))));

}

print_r($array);

gives me:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 5th-Element
                    [1] => 11-02-2012
                    [2] => http://www.5thelementrocks.co.uk/
                    [3] => 5th Element are a 5 piece classic rock covers band gigging in venues across the North-West and Wales. Our set lists include tracks by all the greats, including AC/DC, The Cult, Muse, Bon Jovi, Nirvana, Whitesnake, The Darkness, Ozzy Osbourne, and many more. </p><p>We are a high quality, high energy, experienced classic rock band who work hard and play hard to get the audience going and to make sure each gig is a pro performance. Whether were playing for a crowd of one or one thousand, we always give 110% to keep you shakin all night long!
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => BBGM
                    [1] => 25-02-2012
                    [2] => http://nwb.co/bbgm
                    [3] => BBGM are four 40-50 something musicians (twin guitars, vocals, bass & drums) who were all in various bands years ago, playing and touring all over the North of England & Europe in the 1980s including working and recording with the now legendary producer Gil Norton.</p><p>In 2007 they got together to form BBGM to gig again. Now an established band on the Northwest circuit we are currently gigging throughout the North West and North Wales playing classic rock covers from the 70's 80's and 90's throwing in one or two original tracks penned over the years.
                )
        )

    [2] => Array
        (
            [0] => Array
                (
                    [0] => Plastic-Sarcasm
                    [1] => 18-02-2012
                    [2] => http://www.facebook.com/pages/PLASTIC-SARCASM/284242054943613?sk=info
                    [3] => Four lads who are still burning. Having the desire to kick ass every now and then through the music they create.</p><p>Originally formed in 1978 by current member Phil Narayan together with Paul Wynne, Phil Tonge and Baz Yates, the Band played in the Punk Rock scene era in and around Bolton. Having not played guitar (but played drums for a couple of years from 1986 1989) on stage for over thirty years, Phil Narayan couldn't resist a late urge to enjoy the feeling of playing live on stage once again. Regularly practising with PLUM ( joined the band as singer in 1980) who, now plays Bass guitar and sings, the pair set about making the dream happen once again. They recruited Gordon Connolly for an extra guitar who has been playing throughout his life with various bands, in September 2010. Finally, drummer Gag Martin joined up in reply to an advert at the local rehearsal studios in May 2011.</p><p>"Having had 9 practice / Jammin sessions the band played their first gig in Little Lever on 17th December 2011 where all the old Punk songs were revived. The gig was a screaming success and it is the intention to do more gigs in 2012 when the band will gradually introduce their own numbers more and more as gigs go by."
                )
        )

    [3] => Array
        (
            [0] => Array
                (
                    [0] => Whipcord
                    [1] => 17-02-2012
                    [2] => http://www.facebook.com/whipcord
                    [3] => Doobie Brothers in Bad Brains t-shirts, whistling The Hollies on the way to a Pentagram gig, reading The Wire...it's rock n roll!!</p><p>Whipcord are a stentorian rock n roll power trio from Salford, Manchester UK. Within the noise is a classicist rock feel, drowning in a tar pool of punk rock fury. Being described as the bastard child of Motorhead and Foo Fighters. and that of polished anarchy, not unlike The Whos live shows.
                )
        )
)

aha nearly done.

ps I would like foreach to list by dates stated in each txt file, it currently lists alphabetically from filenames...

Cœur
  • 37,241
  • 25
  • 195
  • 267
DJ-P.I.M.P
  • 105
  • 2
  • 6
  • 15
  • +1 for spending so much time on a question. – Tim Feb 18 '12 at 16:31
  • 1
    You know that this will be much slower than DB right?! Possible encoding problems, etc... Just saying – jribeiro Feb 18 '12 at 16:33
  • i understand, but i cannot use db, for some reason mysql wont install on my machine, but i prefer txt files anyway, as much safer :)..... – DJ-P.I.M.P Feb 18 '12 at 16:34
  • the amount of dodgy chinese bots ive had trying to access db that doesnt even exist, it smuch safer on flat files, and i would presume to load data into each array for each event would be a simple file_get_contents, but im not sure how to implement – DJ-P.I.M.P Feb 18 '12 at 16:35
  • @DJ-P.I.M.P That's an incredibly over-generalized statement to say that flat files are more secure than mysql. There are just as many bots (if not more) trying to ssh or remote into your server to access your files. – Mike B Feb 18 '12 at 16:51

3 Answers3

1

Borrowed a bit of Jribeiro's code to actually read the files into the two-dimensional array.

$items = array();
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        $fp = fopen("$file","r");

        while($line = fgets($fp)){
            $parts = explode("::::",$line);
            $newArr["Name"] = $parts[0];
            $newArr["Date"] = $parts[1];
            $newArr["Link"] = $parts[2];
            $newArr["Writeup"] = $parts[3];
            $items[] = $newArr;  // add newArr to items
        }
        fclose($fp);
    }
    closedir($handle);
}

print_r($items);

Then, to loop through the $items array:

foreach($items as $item){
    $name = $item["Name"];
    echo "Name is $name<br>";
    // etc
}

Although, I'm required to inform you to look into using MySQL to do this as it is much easier, safer, and more powerful than using a flat text file.

Tim
  • 14,447
  • 6
  • 40
  • 63
  • this looks promising, but there is a different .txt file for each event, as i need to search for the filename when loading the dynamic page, if the filename doesnt exist, it forwards to another page – DJ-P.I.M.P Feb 18 '12 at 16:39
  • thanks for taking the time to answer tho, and maybe there is another way to write this for multiple files, – DJ-P.I.M.P Feb 18 '12 at 16:40
  • i did try to explain as much as posible lol, i have been rattling my brains for hours trying to figure out how to word this expression and the logic behind it – DJ-P.I.M.P Feb 18 '12 at 16:44
  • but i am very greatful for any help i get – DJ-P.I.M.P Feb 18 '12 at 16:45
  • print_r($items) shows an empty array, so the foreach is not doing anythign for now, however i know the foreach will work, then the array $items has been filled with values – DJ-P.I.M.P Feb 18 '12 at 16:50
  • i know i know, but mysql wont run on my machine, and i cant afford to reinstall apache php and mysql in 1 package as i cannot afford site downtime – DJ-P.I.M.P Feb 18 '12 at 16:54
  • and i have many advanced server configs that i wouldnt like to have to implement again, as my site wont work without these server configs sorry – DJ-P.I.M.P Feb 18 '12 at 16:59
  • make sure you're setting `$dir` to a useful value – Tim Feb 18 '12 at 18:38
  • $dir is the first var. i define :) ..... question edited with solution.... was some random code i juggled together but worked :) – DJ-P.I.M.P Feb 19 '12 at 03:55
  • this lists in alphabetical order, how could i make foreach list them by date (most recent date first)..... (date example in original question ) thanks m8 – DJ-P.I.M.P Feb 19 '12 at 03:58
  • You could add them to the array associatively, and sort by that, but then you'd run into trouble when there were multiple items on one day. You really gotta get into MySQL here, buddy... – Tim Feb 19 '12 at 16:10
  • i wanted to, i installed on server but php cant connect, i can mod code to add each event div inside another div with date added as div id, if that would help.... can write date in any format necessary :) – DJ-P.I.M.P Feb 19 '12 at 20:37
1

If you want the number of files in dir you can try this:

function fileCounter($dir){
    $counter = 0;
    if ($handle = opendir($dir)) {
      //echo "Directory handle: $handle\n";
      //echo "Files:\n";
      /* This is the correct way to loop over the directory. */
      while (false !== ($file = readdir($handle))) {
          //echo "<BR>".$counter." - $file";
          $counter++;
      }
      closedir($handle);
    }
    $counter -= 1; // in order to exclude '.' and '..', as well as start the counter on 1
    return $counter;
}
jribeiro
  • 3,387
  • 8
  • 43
  • 70
  • the code i have already written today lists all filenames in an array of its own, and removes the '.' and '..' and i already used the func $count = count($files) – DJ-P.I.M.P Feb 18 '12 at 16:42
  • so i can technically count the amount of array values if i need a variable of how many events there is..... however i am having trouble adding each of the text files data into an array so that i can loop over each one and output data from each one – DJ-P.I.M.P Feb 18 '12 at 16:43
  • ohh sorry misunderstood... It seems the answer above is on the right way. i'll check by later to see if this is solved :) – jribeiro Feb 18 '12 at 16:52
0

I'm actually not quite sure if i understood your problem correctly. But at the end you want to store a nested array $events in a flat file and read it back to an array? I would suggest using serialize to do this, then it's quite simple:

$events = array ( array ( Name => event-1,
                          Date => date-1,
                          Link => link-1,
                          Writeup => event-info ),

                  array ( Name => event-2,
                          Date => date-2,
                          Link => link-2,
                          Writeup => event-info ),

                  array ( Name => event-3,
                          Date => date-3,
                          Link => link-3,
                          Writeup => event-info )
                        );
file_put_contents("/foo/bar",serialize($events)); // BAM, it's in the file :)
//reading it back is equally simple
$events2 = unserialize(file_get_contents("/foo/bar"));
lawl0r
  • 840
  • 6
  • 16
  • no sorry, i have a few flat files in a folder, each with a filename of the event, with details of each event in each file..... i need to read and output each txt files details, sorted by earliest date, to furthest date, and output each of the text files details – DJ-P.I.M.P Feb 18 '12 at 16:52