Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Skrypt Waluty - Pobierz z NBP
Dr.VaNs
post
Post #1





Grupa: Zarejestrowani
Postów: 30
Pomógł: 0
Dołączył: 12.10.2007

Ostrzeżenie: (0%)
-----


Witam,


kiedyś miałem do tego celu własny skrypt ale go zapodziałem gdzieś, teraz znowu potrzebuje coś podobnego ale czasu na napisanie nie mam.

W skrócie:

Prosty skrypt pobierający z NBP kurs Walut i od razu wyświetlający 5 walut (zdefiniowane)

Wiem że coś takiego jest opartego o curl i pregmatch ale nie umiem znaleźć tego, bo mój skrypt był też oparty o coś zbliżonego.

Pozdrawiam.
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
nexis
post
Post #2





Grupa: Zarejestrowani
Postów: 1 012
Pomógł: 109
Dołączył: 26.09.2003
Skąd: nexis.pl

Ostrzeżenie: (0%)
-----


  1. <?php
  2. class Nbp
  3. {
  4. private $_url;
  5. private $_cache = 'nbp';
  6.  
  7. public function __construct($url = 'http://www.nbp.pl')
  8. {
  9. $this->_url = $url;
  10. }
  11.  
  12. public function getExchangeRates()
  13. {
  14. $xml = $this->_getXml();
  15. $p = xml_parser_create();
  16. xml_parse_into_struct($p, $xml, $vals, $index);
  17. xml_parser_free($p);
  18. $nbp = array();
  19. foreach($index['NAZWA_WALUTY'] as $value) {
  20. $nbp[$vals[$value+4]['value']] = str_replace(',', '.', $vals[$value+6]['value']);
  21. }
  22. return $nbp;
  23. }
  24.  
  25. public function get($code)
  26. {
  27. $rates = $this->getExchangeRates();
  28. if (!isset($rates[$code])) {
  29. throw new Exception('Currency does not exist!');
  30. }
  31. return $rates[$code];
  32. }
  33.  
  34. public function getEuro()
  35. {
  36. return $this->get('EUR');
  37. }
  38.  
  39. private function _getXml()
  40. {
  41. $filepath = sprintf('%s/%s.xml', $this->_cache, date('Y-m-d'));
  42. if (file_exists($filepath)) {
  43. return file_get_contents($filepath);
  44. } else {
  45. $html = file_get_contents($this->_url . '/kursy/kursya.html');
  46. $pattern = '/\/kursy\/xml\/(.*?)\.xml/';
  47. preg_match_all($pattern, $html, $matches);
  48. if (!isset($matches[0][0])) {
  49. throw new Exception('Unable to find XML filepath!');
  50. }
  51. $xml = file_get_contents($this->_url . $matches[0][0]);
  52. if (!file_exists($this->_cache)) {
  53. if (!mkdir($this->_cache)) {
  54. throw new Exception('Unable to create cache directory!');
  55. }
  56. }
  57. if (!file_put_contents($filepath, $xml)) {
  58. throw new Exception('Unable to save file in cache directory!');
  59. }
  60. return $xml;
  61. }
  62. }
  63. }
  64.  
  65. $nbp = new Nbp();
  66. echo $nbp->getEuro();
  67. echo $nbp->get('USD');
  68. print_r($nbp->getExchangeRates());
  69. ?>


Ten post edytował nexis 11.09.2009, 21:29:11
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 5.10.2025 - 13:33