PHPBuilder - The ABC's of PHP - Part 10 - The Final Installment Page 2

RSS Twitter

The ABC's of PHP - Part 10 - The Final Installment - Page 2

by: PHP Builder Staff
June 2, 2009

The rest of the loop is a sequence of 'preg_matches' wrapped up in an if-then statement that only executes if the 'in_story' variable is true.

if($in_story) {
        $current_story['title'] = $matches[1];

      .. More preg matches follow here for each tag ..

When a 'preg_match' matches on a line containing a tag, we then save the contents of that tag into the 'current_story' array, once we come back out of that story the now filled array is added to the main 'storys' array to form a list of stories found in the XML feed.
They're pretty much all the same, but the one that grabs the date deserves a little extra attention:


Rather than just assign the found text to a single variable, we use two functions that are part of the series of functions for handling text (These are detailed in the strings part of the PHP manual). The 'explode' function takes a sequence of characters and a string, and returns an array of single strings, created by splitting the larger string on the boundaries formed by the character sequence, EG:
If $name = "Peter-#-Shaw", was used with '$result = explode("-#-",$name)' then you would end up with an array called 'result' that would contain 'peter' in element [0] and 'shaw' in element [1].
The trim function just removes excess white space from the ends of the input, so '$result = trim(" Peter Shaw ")' would make 'result' equal to just 'Peter Shaw', we often use trim and explode together, especially in cases such as above where the boundary is a single space, this prevents empty slots in the array by removing any space from the edges that does not constitute a separator between words.
In our script here, the time and the date of publication are separated by a space, so we use 'trim' & 'explode' to separate them into two individual items in the array.
Once we reach the end of this 'foreach' loop that's the hard part of the script behind us, the rest is just to display the results.
The next part down creates another array, this time from single strings:

$styles = array();
$styles['post'] = "{padding: 0px; margin: 0 0 20px 0; clear: <clipped>……

This array holds the styles for the script to allow us to use CSS inline to style the results. Now normally, you would use a separate style sheet, and share it across the whole site. Then use the HTML link tag, however in this case I was reading the PHP manual chapter on the 'foreach' function and I discovered something interesting…

« Previous Page
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.




(Maximum characters: 1200). You have characters left.