How to fetch gold/sliver price in Nepal
In this post I will go through PHP code to fetch gold/silver price data from any site content without any API. Here I am using PHP core functions to get content from site and manipulate string content to get required value because content may contains unnecessary html strings.
Gold/Silver price always changes and it’s been part of daily uses data. If you want to show current price of gold/silver in your website or app , you can use this code.
$url = 'https://www.hamropatro.com/gold/';
$content = file_get_contents($url);
$d1 = explode('<ul class="gold-silver" style="margin: 0">', $content);
$d2 = explode("</ul>", $d1[1]);
$d3 = $d2[0];
$d4 = explode('<li', $d3);
$arrName = array();
$arrPrice = array();
$pushName = true;
foreach ($d4 as $key => $value) {
if ($key == 0) {
continue;
}
$final = $this->getStringBetween($value, ">", "<");
if ($pushName) {
array_push($arrName, $final);
$pushName = false;
} else {
array_push($arrPrice, trim($final));
$pushName = true;
}
}
$finalArray = array();
foreach ($arrName as $key => $value) {
$tempArray["name"] = $value;
$tempArray["price"] = $arrPrice[$key];
array_push($finalArray, $tempArray);
}
$finalJson = json_encode($finalArray);
echo $finalJson;
function getStringBetween($str, $start, $end) {
$subtring_start = strpos($str, $start);
$subtring_start += strlen($start);
$size = strpos($str, $end, $subtring_start) - $subtring_start;
return substr($str, $subtring_start, $size);
}
NB: it may give error if any changes in the content of site.