Jump to content


This topic is now archived and is closed to further replies.


Help With Foreach

Recommended Posts


I have a file with a table on it:


I want to only show the rows with Cats. So far I have:

[code]$content = file_get_contents($url);  
$content[1] = str_replace("<table>", "", $content[1]);
$content[1] = str_replace("<tr><td>", "", $content[1]);
$content[1] = str_replace("</td></tr>", "", $content[1]);
$content[1] = str_replace("</table>", "", $content[1]);
$content[1] = str_replace("</td><td>", "|", $content[1]);[/code]

If I echo $content[1] I will get:


I obviously want to explode the data at each "|" but how do I loop through each line? I have been trying to figure out [b]foreach[/b] because that seems to be what I need, but I can't seem to figure it out. :(

Thanks in advance!


Share this post

Link to post
Share on other sites
Why don't you store this information in a database instead of a marked up file, that way you can make it take any form you want, instead of having to rip formatting off the previous entry.

If a database isn't an option then I have a second solution for you that will get around this formating business. Create a text file somewhere with the information stored like so...


Then use open the file and get the contents with the file() function. You'll now have an array of strings, where each line is an entry in the array. So then you can eregi each array value for the string "Cat" if found you display that, exploding the string and then putting it into a table format. Otherwise you skip it and move on. This has the added benefit of making it easy to switch to dogs later, or both. It also let's you apply any formatting you want.

Share this post

Link to post
Share on other sites
If you want to get each line seperatly you'll need to use explode, like so:
$content[1] = explode("\n", $content[1]);
Now each line will be in its own array you'll this:

x being the line number. But rememeber arrays start at zero. SO if you want line 5 you'll need to replace x with 4 like so:
$content[1][4] // line5

Hope that helps.

Also you can use a foreach loop to do the dirty work for you to get each line, like so
[code]foreach($content[1] as $key => $value)
    echo "\$content[{$key}] = \"$value\"<br />\n";

Then if you want to get the Pet, Owner and address on their own use the following in your foreach loop instead:
[code]foreach($content[1] as $key => $value)
    ($pet, $owner, $address) = explode("|", $content[1][$key]);

    echo $owner . ' has a ' . $pet . ' which lives at ' . $address;

Hope that helps.

Share this post

Link to post
Share on other sites
Thanks wildteen88! It worked.

And thanks for the suggestion Buyocat. It's always a good idea to make it as simple as possible.

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.