Plug in PHP 100 POWER SOLUTIONS- P62 ppt

5 141 0
Plug in PHP 100 POWER SOLUTIONS- P62 ppt

Đang tải... (xem toàn văn)

Thông tin tài liệu

C h a p t e r 1 0 : A P I s , R S S , a n d X M L 271 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 271 The second book’s details can therefore be accessed like this (and so on): $title = $result[1][1][0]; $author = $result[1][1][1]; $publisher = $result[1][1][2]; $date = $result[1][1][3]; $description = $result[1][1][4]; $thumbnail = $result[1][1][5]; $information = $result[1][1][6]; $preview = $result[1][1][7]; However, you will probably want to use a foreach loop to iterate through the $result[1] array, passing each element to another array with a name such as $book, like this: foreach($result[1] as $book) { echo "<img echo "<a href='$book[6]'>$book[0]</a> ($book[2], " . "$book[3])<br />$book[4]"; if ($book[7]) echo " (<a href='$book[7]'>preview</a>)"; echo "<br clear='left' /><br />"; } Because all eight items are provided separately, you can choose exactly how you wish to lay out a book’s details. In the preceding code, the thumbnail image in $book[5] is displayed aligned to the left and with a 1-pixel border. Then the book title in $book[0] is used as a text hyperlink for the book’s information page in $book[6]. Alongside this, the book’s publisher and publication date in $book[2] and $book[3] are added within brackets, followed by a <br /> tag and the book’s description in $book[4]. After this, if the book has a preview, identified by $book[7] having a value, then a link is provided to it, enclosed in brackets. Finally, the book thumbnail’s left alignment is cleared using the tag <br clear='left' />, and then another <br /> tag is used to separate book details from each other. If you want to only return results for books where the whole text is available in the summary, generally because they are out of copyright control or because their authors have allowed the entire contents to be released, just replace the preceding call to the plug-in with this one: $result = PIPHP_SearchGoogleBooks($search, 1, 20, 'full'); Or, to allow results with either partial or full previews, you could use: $result = PIPHP_SearchGoogleBooks($search, 1, 20, 'partial'); You can also support paging through the search results by changing the start argument for the book number at which returned results should begin, and re-calling the plug-in. 272 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 272 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s The Plug-in function PIPHP_SearchGoogleBooks($search, $start, $count, $type) { $results = array(); $url = 'http://books.google.com/books/feeds/volumes?' . 'q=' . rawurlencode($search) . '&start-index=' . "$start&max-results=$count&min-viewability=" . "$type"; $xml = @file_get_contents($url); if (!strlen($xml)) return array(FALSE); $xml = str_replace('dc:', 'dc', $xml); $sxml = simplexml_load_string($xml); foreach($sxml->entry as $item) { $title = $item->title; $author = $item->dccreator; $pub = $item->dcpublisher; $date = $item->dcdate; $desc = $item->dcdescription; $thumb = $item->link[0]['href']; $info = $item->link[1]['href']; $preview = $item->link[2]['href']; if (!strlen($pub)) $pub = $author; if ($preview == 'http://www.google.com/books/feeds/users/me/volumes') $preview = FALSE; if (!strlen($desc)) $desc = '(No description)'; if (!strstr($thumb, '&sig=')) $thumb = 'http://books.google.com/googlebooks/' . 'images/no_cover_thumb.gif'; $results[] = array($title, $author, $pub, $date, $desc, $thumb, $info, $preview); } return array(count($results), $results); } Convert Currency The final plug-in in this chapter allows you to produce up-to-date currency conversions between 34 major currencies. The data used is supplied by the European Central Bank and is based on the prices of each currency relative to the euro at the previous trading session’s 80 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 273 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 273 close of business. Figure 10-13 shows the plug-in being used to convert 100 U.S. dollars into UK pounds. About the Plug-in This plug-in takes a value and currencies to convert it from and to. Upon success, it returns a floating point number, accurate to two decimal places, representing the value of the amount given when converted to the new currency. On failure, it returns the value FALSE. It requires these arguments: • $amount The amount of money to convert • $from The abbreviation for the source currency • $to The abbreviation for the destination currency The available currencies and their abbreviations are: AUD = Australian Dollar BGN = Bulgarian Lev BRL = Brazilian Real CAD = Canadian Dollar CHF = Swiss Frank CNY = Chinese Yuan CZK = Czech Koruna DKK = Danish Krone EEK = Estonian Kroon EUR = European Euro GBP = British Pound HKD = Hong Kong Dollar HRK = Croatian Kuna HUF = Hungarian Forint IDR = Indonesian Rupiah INR = Indian Rupee JPY = Japanese Yen KRW = South Korean Won LTL = Lithuanian Litas LVL = Latvian Lats MXN = Mexican Peso MYR = Malaysian Ringgit NOK = Norwegian Krone NZD = New Zealand Dollar PHP = Philippine Peso PLN = Polish Zloty RON = Romanian Lei RUB = Russian Ruble SEK = Swedish Krona SGD = Singapore Dollar THB = Thai Baht TRY = Turkish Lira USD = U.S. Dollar ZAR = South African Rand FIGURE 10-13 Using this plug-in, you can instantly convert between 34 currencies. 274 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 274 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s Variables, Arrays, and Functions $url String containing the URL for the European Central Bank exchange rates page $data String containing the result of loading in $url $ptr1 Integer pointer to the start of the currency data $ptr2 Integer pointer to the end of the currency data $main Array in which the currencies and prices are stored $lines Array of data lines extracted from $data $line String containing a line of data from $lines $l String containing the left half of a currency/value pair $r String containing the right half of a currency/value pair How It Works This plug-in loads the XML page that the European Central Bank maintains of currency rates compared to the euro into the variable $data. If no data is returned, then there was an error and FALSE is returned. Otherwise, instead of converting the XML data into an object as some of the other plug- ins do, the information needed is easily extracted with just a few PHP commands. First, the start and end of the section of XML of interest are put in the variables $ptr1 and $ptr2. This is done using the strpos() function to search for certain strings in the file. The contents of $data are then cropped down to just that section using the substr() function, then a few keywords, tags, and other pieces of XML are replaced with values of more use to the plug-in, and whitespace is also removed. This leaves $data containing just 33 lines, each of which is a currency/value pair in relation to the euro at the time of closing of the previous day’s trading session. Each line is separated from the others with an @ symbol, and the currency abbreviations are separated from their values by | symbols. Using these as separators, the contents of $data are split into the array $lines at each of the @ symbols using the explode() function. Then, using a foreach loop, each individual line is processed into the associative array $main by using explode() to separate the currencies from their values at the | symbol. The parts are placed in $l and $r using the list() function, and from there the values are assigned to the $main array. At this point, the $main array has 33 currencies, each one accessible by its abbreviation. For example, $main['DKK'] will return the value of the Danish krone against the euro. But there is one currency missing because all the other values are set against it, and that’s the euro, with an abbreviation of EUR. Therefore that gets added to the $main array with a value of 1, because that is its value in relation to itself. Next, both the values of $from and $to are set to uppercase (if they aren’t already) using the strtoupper() function, and then they are also checked to ensure they both have an associated value in the $main array. If either of them doesn’t, then an unknown abbreviation was used and so the value FALSE is returned. Otherwise, a quick calculation converts one currency to another using the formula New value = Original value / From value * To value. The result is then passed through the sprintf() function to ensure it has exactly two decimal places and the final result is then returned. C h a p t e r 1 0 : A P I s , R S S , a n d X M L 275 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 275 If you need more decimal places in your returned values, you can change the %.02f to another string such as %.04f for four decimal places, and so on. How to Use It To use the plug-in, you pass it a value to convert, along with abbreviations representing currencies from and to which the value should be converted, like this: $amount = 100; $from = 'USD'; $to = 'GBP'; $result = PIPHP_ConvertCurrency(100, $from, $to); if (!$result) echo "Conversion failed."; else echo "$amount $from is $result $to"; If you plan to call this function a lot, you would be well advised to save the contents of $data once per day, and return conversions based on the saved values. This will stop your program excessively calling the ECB server, which is not necessary anyway, because the data there is only updated daily. The Plug-in function PIPHP_ConvertCurrency($amount, $from, $to) { $url = 'http://www.ecb.europa.eu/stats/eurofxref/' . 'eurofxref-daily.xml'; $data = file_get_contents($url); if (!strlen($data)) return FALSE; $ptr1 = strpos($data, '<Cube currency'); $ptr2 = strpos($data, '</Cube>'); $data = substr($data, $ptr1, $ptr2 - $ptr1); $data = str_replace("<Cube currency='", '', $data); $data = str_replace("' rate='", '|', $data); $data = str_replace("'/>", '@', $data); $data = preg_replace("/\s/", '', $data); $main = array(); $lines = explode('@', substr($data, 0, -1)); foreach($lines as $line) { list($l, $r) = explode('|', $line); $main[$l] = $r; } $main['EUR'] = 1; $from = strtoupper($from); $to = strtoupper($to); if (!isset($main[$from]) || !isset($main[$to])) return FALSE; return sprintf('%.04f', $amount / $main[$from] * $main[$to]); } . Functions $url String containing the URL for the European Central Bank exchange rates page $data String containing the result of loading in $url $ptr1 Integer pointer to the start of the currency data $ptr2 Integer. pointer to the end of the currency data $main Array in which the currencies and prices are stored $lines Array of data lines extracted from $data $line String containing a line of data from $lines $l String. split into the array $lines at each of the @ symbols using the explode() function. Then, using a foreach loop, each individual line is processed into the associative array $main by using explode()

Ngày đăng: 07/07/2014, 08:20

Mục lục

  • 1 Building a Development Server

    • Windows XP, Windows Vista, and Windows 7

      • Reinstalling Zend Server CE

      • Upgrading Zend Server CE

      • Ubuntu and Debian Linux

        • Uninstalling

        • Fedora, RHEL, and CentOS Linux

          • Installing MySQL

          • Other Versions of Linux

            • Installing MySQL

            • Mac OS X 10.4 Plus on Intel Chips

              • Document Root

              • Configuring Error Handling in Zend Server CE

              • And Now You’re Set to Go

              • 2 Using the Plug-ins

                • Using include

                  • include_once

                  • Correctly Inserting PHP code

                    • Inserting HTML

                    • Including PHP Files from Other Servers

                    • 3 Text Processing

                      • Plug-in 1: Wrap Text

                        • About the Plug-in

                        • Variables, Arrays, and Functions

                        • How to Use It

                        • Plug-in 2: Caps Control

                          • About the Plug-in

                          • Variables, Arrays, and Functions

                          • How to Use It

                          • Plug-in 3: Friendly Text

                            • About the Plug-in

                            • Variables, Arrays, and Functions

                            • How to Use It

Tài liệu cùng người dùng

Tài liệu liên quan