Couple days ago, i was asked by a friend to make a small currency exchange script in PHP. With slow internet connection and so short amount of time, the best thing i could think of was grabbing the number from available currency rate site like this. With curl and PCRE function, i finished the script in no time. :p
That’s evil of course.
So, i create the following script as my apology. I use FoxRate currency converter API. Be careful though, you can not run the script too fast, wait for awhile before sending the next request. That’s what happen when you use a free web service. I guess.
Anyway, it’s 2 a.m in the morning here. Gotto go to bed. Night night.
function convertcurrency($from,$to,$amount) { $xml = " <?xml version='1.0'?> <methodcall> <methodname>foxrate.currencyConvert</methodname> <params> <param> <value> <string>$from</string> </value> </param> <param> <value> <string>$to</string> </value> </param> <param> <value> <double>$amount</double> </value> </param> </params> </methodcall>"; $url = "http://www.foxrate.org"; $header = "POST /rpc/ HTTP/1.0 \\r\\n"; $header .= "Host: foxrate.org \\r\\n"; $header .= "MIME-Version: 1.0 \\r\\n"; $header .= "Content-length: ".strlen($xml)." \\r\\n"; $header .= "Content-transfer-encoding: text \\r\\n"; $header .= "Document-type: Request \\r\\n"; $header .= "Connection: close \\r\\n\\r\\n"; $header .= $xml; $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $xmlresponse = curl_exec($ch); curl_close($ch); $sxml = new SimpleXMLElement($xmlresponse); $xxml = $sxml->xpath("params/param/value/struct/member"); foreach ( $xxml as $v ) { if ( $v->name == "flerror" ) { $errflag = $v->value->int; } if ( !$errflag ) { return false; break; } if ( $v->name == "amount" ) { return $v->value->double; } } }
Sample usage:
$ret = convertcurrency("JPY","IDR",1); if ( $ret ) { echo "1 JPY = $ret IDR"; } else { echo "Wrong currency code or you're too fast to fetch, wait for awhile."; }
Use google to convert currency. http://www.google.com/help/features.html#currency