Tutorial
Retrieval of data from the Internet using PHP
Introduction
My project, An Online User Interface of Tracking Stock Portfolios, relied on Yahoo! Finance for data about stocks such as prices and changes in price. I obtained these data through the PHP function preg_match. Format and operation
The basic form of the function is:
The function searches subject for matches of pattern, returning an integer of the number of matches foundeither 0 for no matches, or 1 (the function discontinues the search after finding a match).
Results
The results of the search are in matches, if that optional variable is in the call to preg_match. Text matching the complete pattern given is found in $matches[0]. The pattern located in parentheses in the call to preg_match is found in $matches[1]; the number in the brackets after $matches corresponds to the depth of the nesting of patterns located in nested parentheses. I did not use flags at any point during my project.
Other notes
Example
The following code displays the stock price of the listing designated by the ticker symbol sent to the function. The function obtains the string to be searched by retrieving the source code of the Yahoo! Finance page that corresponds with the given ticker symbol. The search is then conducted and the result is printed to the screen. The code must be placed within the tags indicating PHP code.
//retrieve obtains price of $symbol
function retrieve($symbol)
{
//obtain a page containing data regarding $symbol
$url = "http://finance.yahoo.com/q?s=$symbol&d=t";
//if opening unsuccessful, exit function
if (!($fp = fopen($url, "r")))
{
echo "Unable to open page.";
exit;
}
//if opening successful, read 100000 bytes from opened page
$contents = fread($fp, 100000);
//close page obtained
fclose($fp);
//if price of $symbol < 1000 dollars, it is stored in $quote
if (preg_match("/([0-9]+\.[0-9]+)/", $contents, $quote))
//print value of index or listing
echo "$quote[1]";
}
//end function retrieve
Conclusion
In my project, $pattern was changed in order to obtain several data for a single stock. I hope that this tutorial will prove helpful in your endeavors with preg_match.
Source: php.net.