Diễn đàn » PHP - HTML - CSS » Code lấy thông tin tỷ giá vàng SJC và ngoại tệ
Avatar
tờ ròm Tôi yêu Việt Nam
Tính năng:
- Lấy tỷ giá vàng SJC, ngoại tệ: USD, SGD,...

Hướng dẫn:
Code rất đơn giản như sau:

$tygia = new class {
  function sjc($get_city = null, $type = null)
  {
    $xml_url = 'https://XXX.workers.dev/xml/tygiavang.xml';
    $xml = simplexml_load_file($xml_url);
    $city = $xml->xpath('//city[@name="' . $get_city . '"]');
    $item = $city[0]->item;
    $buy = $item['buy'];
    $sell = $item['sell'];
    if ($get_city == 'Hồ Chí Minh') {
      switch ($type) {
        case '1':
          $type_name = 'Vàng SJC 1L - 10L';
          break;
        case '2':
          $type_name = 'Vàng nhẫn SJC 99,99 1 chỉ, 2 chỉ, 5 chỉ';
          break;
        case '3':
          $type_name = 'Vàng nhẫn SJC 99,99 0,5 chỉ';
          break;
        case '4':
          $type_name = 'Vàng nữ trang 99,99%';
          break;
        case '5':
          $type_name = 'Vàng nữ trang 99%';
          break;
        case '6':
          $type_name = 'Vàng nữ trang 75%';
          break;
        case '7':
          $type_name = 'Vàng nữ trang 58,3%';
          break;
        case '8':
          $type_name = 'Vàng nữ trang 41,7%';
          break;
      }
      $item = $city[0]->xpath('//item[@type="' . $type_name . '"]');
      $buy = $item[0]['buy'];
      $sell = $item[0]['sell'];
    }
    return [
      'buy' => $buy,
      'sell' => $sell
    ];
  }

  function currency($CurrencyCode = null)
  {
    $xml_url = 'https://portal.vietcombank.com.vn/Usercontrols/TVPortal.TyGia/pXML.aspx';
    $xml = simplexml_load_file($xml_url);
    $tygia = $xml->xpath('//Exrate[@CurrencyCode="' . $CurrencyCode . '"]');
    $buy = $tygia[0]['Buy'];
    $transfer = $tygia[0]['Transfer'];
    $sell = $tygia[0]['Sell'];
    return [
      'buy' => $buy,
      'transfer' => $transfer,
      'sell' => $sell
    ];
  }
};


Sử dụng:
 // lấy tỷ giá vàng sjc
$sjc_hanoi = $tygia->sjc('Hà Nội');
echo 'SJC Hà Nội: <br/>Mua: ' . $sjc_hanoi['buy'] . ' - Bán: ' . $sjc_hanoi['sell'];
echo '<br/>';
$sjc_hcm_1 = $tygia->sjc('Hồ Chí Minh', 1);
echo 'SJC Hồ Chí Minh 1L - 10L: <br/>Mua: ' . $sjc_hcm_1['buy'] . ' - Bán: ' . $sjc_hcm_1['sell'];
echo '<br/>';

// lấy tỷ giá ngoại tệ USD
$usd = $tygia->currency('USD');
echo 'USD: <br/>Mua: ' . $usd['buy'] . ' - Chuyển khoản: ' . $usd['transfer'] . ' - Bán: ' . $usd['sell'];


Thông tin tỷ giá vàng SJC, mình lấy từ:https://sjc.com.vn/xml/tygiavang.xml nhưng không may mắn thay, ở bển chặn thứ gì đó mà mình không thể lấy được nội dung file của bển.

Nên mình đã lấy trung gian qua Cloudflare Workers như sau:
Tạo Worker Page, gán và deploy code sau:
const baseHost = "https://sjc.com.vn"

/**
* gatherResponse awaits and returns a response body with appropriate headers.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/

async function gatherResponse(response) {
    const {
        headers
    } = response
    return {
        body: await response.body,
        extra: {
            status: response.status,
            statusText: response.statusText,
            headers: headers
        }
    }
}

async function handleRequest(request) {
    const requestUrl = new URL(request.url)
    const proxyRequest = new Request(baseHost + requestUrl.pathname + requestUrl.search, {
        method: request.method,
        headers: request.headers,
        cf: {
            cacheTtl: 10,
            cacheEverything: true
        }
    })
    const response = await fetch(proxyRequest)
    const results = await gatherResponse(response)
    return new Response(results.body, results.extra)
}

addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})


Sau đó thay XXX ở đoạn code php thành tên page mà bạn vừa tạo được.

Wordpress cũng có người share API, bạn có thể trích ra từ đó để dùng (toàn là iframe), nhưng nếu bạn không muốn dùng nó thì bạn có thể tham khảo những dòng code này.

Demo:
Đức, Gill, Thanh Tam đã thích bài viết này
Trống!
Trống!
  • BBcode:
  • Markdown: