Home > Web > Basic Parse With PHP – Part One

Basic Parse With PHP – Part One

April 29th, 2006
Comments Off

Quite often, you will want to take the information provided freely on another website and include it on your own. This post will explain how you can do some basic parsing using PHP.

In Part One, I will describe how to obtain value for the current US Dollar exchange rate against 1 Australian Dollar from Yahoo!’s finance site. This is probebly one of the simplest parse requests but it is still quite useful to understand. Here is the current exchange rate:

I will now explain how this is done.

<?
 $open = fopen("http://au.finance.yahoo.com/d/quotes.csv?s=AUDUSD=X&f=sl1&e=.csv", "r");
 $results1 = fread($open, 32);
 fclose($open);
 printf ("1 AUD = %01.4f USD", substr($results1, 11, 12));
?>

This simple program is only 4 lines long.
Line 1: Specifies what URL you are retrieving the quote from and it is being assigned to a varaible named $open.
Line 2: Read the URL and stores the first 32 bytes inside the variable $results1. You can change the byte value of 32 to what ever you feel is necessary to complete a job.
Line 3: Close the connection to the websites specified in the variable $open.
Line 4: Formats the output using printf, to 4 decimal places (float). Only the information contained inside the substr is displayed in this format.

Of course, no one should be writing code without some form of re-usability, so here is the code inside a function that can be called to display the value of any known currency type.

<?
FUNCTION QuoteExchangeRate($from_currency, $to_currency) {
 $open = fopen("http://au.finance.yahoo.com/d/quotes.csv?s=$from_currency$to_currency=X&f=sl1&e=.csv", "r");
 $results1 = fread($open, 32);
 fclose($open);
 printf ("1 $from_currency = %01.4f $to_currency", substr($results1, 11, 12));
}
QuoteExchangeRate("AUD", "USD");
?>

The function named QuoteExchangeRate works in exactly same manner as the first example, but you can now pass to it two variables specifying the exchange rate you are after and the code that Yahoo! finance understands. So QuoteExchangeRate(“AUD”, “USD”); specifies that we are want 1 Australian Dollar (AUD) changed into US Dollars (USD).

You could also set the script up to use values passed on the URL by using QuoteExchangeRate($_GET['from'], $_GET['to']);. You would then need to call the PHP file with the parameters ?from=AUD&to=USD to achieve the same result.

You can specify other currencies very easily, such as QuoteExchangeRate(“AUD”, “GBP”); which will display 1 Australian Dollar in British Pounds:

You can also reverse the lookup by specifying QuoteExchangeRate(“USD”, “AUD”); which will display 1 US Dollar in Australian Dollars:

In Part Two, I will show you have you can take this example and expand it so you can parse ebay auctions based on a search term.

Web ,