PHP获取今日汽油价格接口
Selector.php下载:先把图片文件下载,然后把扩展名改成.zip,最后解压缩
<?php require "selector.php"; function getGasolinePrice() { try { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'http://www.qiyoujiage.com/chongqing.shtml', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', )); $jieguo = curl_exec($curl); curl_close($curl); } catch (Exception $e) { throw new RuntimeException("请求失败"); } $select=new selector(); $regx = "//div[@id='youjia']"; $con=$select->select($jieguo,$regx); $con = $select->select($con, "//dl"); if (empty($con)) { return []; } $qiyou = []; foreach ($con as $k=>$v) { $qiyou[$k]['type']=$select->select($v, "//dt"); $qiyou[$k]['per_price']=$select->select($v, "//dd"); } return $qiyou; } echo json_encode(getGasolinePrice()); /** 输出: [ { "type":"重庆92#汽油", "per_price":"7.54" }, { "type":"重庆95#汽油", "per_price":"7.97" }, { "type":"重庆98#汽油", "per_price":"8.98" }, { "type":"重庆0#柴油", "per_price":"7.20" } ] */