Jump to content

Recommended Posts

Could you please explain the workings of using the foreach statement?

 

Yes, I have spent much time reading on this. Maybe someone has the gift of communicating this to me in an easy to understand manner.

 

Maybe a simple example would help?

 

-I guess I can't comprehend why we need foreach() why can't we just print or echo the $matches[1]?

-Why does the $matches only display one match when there are at least 50 on each page?

 

$CL= Craigslist

 

See.. I am attempting to scrape musician ads from CL, but leave the link intact leading back to CL. I get the information I need , but only one or two ads are scraped. Not only that , but the links are not linking back to CL and also the ads are being mirrored (2 in a row of the same.

 

Here is my current code:

  <?php
$html = file_get_contents("http://southcoast.craigslist.org/muc/");

preg_match_all('/<a href="([^"]+)">([^<]+)<\/a><font size="-1">([^"]+)<\/font>/s', $html,$posts);

foreach ($posts as $post)
{
    print $post[1];
   
// do something with data
}
?> 

 

I think if someone explains the workings of the foreach function I can move on.

 

As always, thanks guys!

 

and btw i think your problem is what array you are trying to loop through.  preg_match_all returns a multi-dimensonal array, based on whether you have things being captured in your pattern (which you do).  I suggest after your preg_match_all, you do this:

 

echo "<pre>";print_r($posts);

 

to get an idea of the structure of the array being returned.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.