file_get_contents and div
What's wrong with my code? I wish to get all dates 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>";
?>
开发者_如何学JAVA
Thanks
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.
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);
Before messing around with REGEX, try HTML Scraping. This HTML Scraping in Php might give some ideas on how to do it in a more elegant and (possibly) faster way.
$doc = new DomDocument;
$doc->Load('http://weather.yahoo.com/');
$doc->getElementById('myLocContainer');
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
Test your response before running the regex search. Then you'll know which part isn't working.
精彩评论