5/5 - (5 bình chọn)

Sau bài chia sẻ code hiển thị tỷ giá ngoại tệ của VCB, hôm nay mình xin chia sẻ tiếp code hiển thị giá vàng SJC. Xài cài này đỡ phải thêm 1 plugin, trong khi nhu cầu đơn giản.

Code hiển thị tỷ giá vàng SJC

function getContentBycURL($url)
{
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

	$headers = array(
	   "Accept: application/json",
	   "Content-Type: application/json",
	   "Content-Length: 0",
	);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	//for debug only!
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

	$resp = curl_exec($curl);
	curl_close($curl);
	return $resp;
}
function tygiavang_sjc() {	
    $data1 = getContentBycURL('https://www.sjc.com.vn/xml/tygiavang.xml');
    $data = new SimpleXMLElement($data1);
    ob_start();    
?>
    <table border="1">
        <tr bgcolor="yellow">
            <td>Thành phố</td>
            <td>Loại</td>
            <td>Bán ra</td>
            <td>Mua vào</td>

        </tr>
    <?php
    foreach($data->ratelist->city as $item){
    ?>
        <tr>
            <td <?php if(count($item->item)>1){?>rowspan="<?php echo count($item->item)?>" <?php }?>><?php echo (string)$item['name']?></td>
            <?php 
            $first=reset($item->item);
            next($item);
            ?>
            <td><?php echo (string)$first['type']?></td>
            <td><?php echo (string)$first['sell']?></td>
            <td><?php echo (string)$first['buy']?></td>
        </tr>
        <?php
        if(count($item->item)>1){
            $isFirst = true;
            foreach($item->item as $t){
                if ($isFirst) {
                $isFirst = false;
                continue;
            }   
        ?>
            <tr>
                <td><?php echo (string)$t['type']?></td>
                <td><?php echo (string)$t['sell']?></td>
                <td><?php echo (string)$t['buy']?></td>
            </tr>
        <?php
            }
        }
        ?>
    <?php
    }
    ?>
    </table>
<?php 
        $tygia_sjc = ob_get_contents();
        ob_end_clean();
        return $tygia_sjc;		
}
add_shortcode('tygiavang_sjc','tygiavang_sjc');

Cách sử dụng

  1. Bạn truy cập vào Giao diện -> Sửa giao diện -> chọn functions.php của theme đang dùng. Dán code vào
  2. Bước tiếp theo là chèn shortcode [tygiavang_sjc] vào nơi bạn muốn hiển thị

Note: Nếu chèn vèo widget mà không hiển thị, bạn chèn thêm code sau vào functions.php của theme đang dùng.

add_filter( 'widget_text', 'do_shortcode' );

Kết quả mẫu

sai gon data code bang gia vang

Cảm ơn đã ghé thăm!

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *