php with preg_match_all() generates no results
I'm trying to use this php script in order to locate a stock quote from yahoo finance. The problem I'm having is that when the script is run it generates no results. This leads me to believe that my regular expression is incorrect, but when I use the same regex on myregextester.com it shows the results that I expect with the given input. Any help will be greatly appreciated. Also, my php may be incorrect for what I'm trying to do.
<html>
<head>
<title>Stock Quote from Nasdaq</title>
</head>
<body>
<?php
// choose stock to look at
$symbol = 'AMZN';
echo "<h1> Stock Quote for $symbol </h1>";
//echo 'this printed (1)<br />';
$theurl = 'http://finance.yahoo.com/q?s=AMZN';
//echo 'this printed (2)<br />';
$contents = file_get_contents($theurl);
//find the part of the page we want and output it
if (preg_match_all('/amzn">([0-9]+\.[0-9]+)/', $contents, $matches)) {
开发者_如何学运维 echo "The price for $symbol: ".$matches[1][0];
} else {
echo "No Results";
}
?>
</body>
</html>
What you are searching for is:
<span id="yfs_l10_amzn">221.37</span>
Your regex would succeed for that.
So your actual problem is retrieving the page. Besides the obnoxious $theurl
variable name, you should just use file_get_contents
instead of fread
etc.
$contents = file_get_contents($theurl);
Worked in your snippet.
I just downloaded the url http://finance.yahoo.com/q?s=AMZN and looked at the page source. Done a seach for /amzn. One match. That was <a href="/marketpulse/AMZN">Market Pul....
Hence no match.
Need to have a rethink.
Escape the >
try this:
preg_match_all('/amzn"\>[0-9]+\.[0-9]+/',$contents, $matches);
精彩评论