tags:

views:

37

answers:

6

Hi,

whats wrong with my code? I wish get all date from but my array is empty.

<?php
$url = "http://weather.yahoo.com/";
$page_all = file_get_contents($url); 

preg_match_all('#<div id="myLocContainer">(.*)</div>#', $page_all, $div_array);

echo "<pre>";
print_r($div_array);
echo "</pre>";
?>

Thanks

A: 

Test your response before running the regex search. Then you'll know which part isn't working.

Peter Anselmo
file_get_contents can use a http stream wrapper, so it's not only for local files
kgb
You learn something new everyday.
Peter Anselmo
A: 

You want to parse a multiline content but you did not use multiline switch of REGEX pattern. Try using this:

preg_match_all('#<div id="myLocContainer">(.*?)</div>#sim', $page_all, $div_array);

Please note that regular expressions is not suitable for parsing HTML content because of the hierachical nature of HTML documents.

eyazici
A: 

try adding "m" and "s" modifiers, new lines might be in the div you need.. like this:

preg_match_all('#<div id="myLocContainer">(.*)</div>#ms', $page_all, $div_array);
kgb
A: 

Before messing around with REGEX, try HTML Scraping. This http://stackoverflow.com/questions/34120/html-scraping-in-php might give some ideas on how to do it in a more elegant and (possibly) faster way.

DrColossos
There is a recent implementation of such a library (allowing to access elements via CSS etc) built on PHP 5.3, using some components of the upcoming Symfony 2. Note: It's still kind of unstable. http://www.phparch.com/2010/04/22/four-new-php-5-3-components-and-goutte-a-simple-web-scraper/
igorw
A: 
$doc = new DomDocument;
$doc->Load('http://weather.yahoo.com/');
$doc->getElementById('myLocContainer');
Ben Shelock
A: 

you need to Excape Special Characters in your Regular Expression like the following

~\<div id\=\"myLocContainer\"\>(.*)\<\/div\>~

also Checkout wheather there is a newline problem or not as mentioned by @eyazici and @kgb