PDA

View Full Version : Using file_get_contents() and explode()



alexjewell
01-11-2007, 09:40 PM
I have a booklist and I've been trying to figure out a way to count up the total number of pages. I think I found it. However, there's a piece of it I don't know how to go about. I have the table containing the table of books as a separate file and I import it into the index; it's called books.php. All books.php contains is that table. Here is an example of a row:



<tr>
<td class="date"><p>January 11, 2007</p></td>
<td class="book-author"><p>Life Everlasting</p></td>
<td class="book-author"><p>Robert Whitlow</p></td>
<td class="genre"><p>Fiction/Susp.<!--fiction--><!--suspense--></p></td>
<td class="pages"><p>403</p></td>
</tr>


(by the way, the comments in the genre section are there for another element of the site - to count up the different genres. I use file_get_contents, then substr_count() to count them)

Now, right now I just add a book's number of pages onto a total number and just echo that. That's a lot of work, and there's room for error...since I'm human, and may mis-add or something.

So this is my idea:


$file = file_get_contents('books.php');

then, use explode to split it to the pages line of each book and get that number.


explode('<table cellpadding...' , $file);

but...all I can do is split it to the first number.

how do I keep splitting AND adding up the numbers to get a final pages count?

do I use a "do, while" or something?

at least I have the idea...now I need some help!

thanks.

alexjewell
01-12-2007, 09:46 PM
Ok - maybe I should use a foreach statement?
HELP?!

djr33
01-12-2007, 10:35 PM
foreach can work, as could some creative use of for or while.

djr33
01-13-2007, 03:17 AM
Solution as per conversation in AIM:

<?php
$f = file_get_contents('books.php');
$segments = explode('<td class="pages"><p>',$f);
$npgs = 0;
$nbks = 0;
foreach ($segments as $s) {
list($num,$extra) = explode('</p>',$s);
if (is_numeric($num)) {
$npgs += $num;
$nbks++;
}
}
echo 'Pages: '.$npgs."<br>\n";
echo 'From '.$nbks.' books.';
?>