如何从网站获取值(在PHP中使用cUrl) [英] How to pull a value from a website ( Using cUrl in PHP)
本文介绍了如何从网站获取值(在PHP中使用cUrl)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以下脚本从某个网站提取值,但是我认为这不是有效的DOM文档,我想知道是否还有其他方法?
I am trying the following script to pull a value from a certain website, however I think this is not a valid DOM Document, I want to know if there is an alternate way?
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://www.indiagoldrate.com/gold-rate-in-mumbai-today.htm');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer))
{
print "Sorry, example.com are a bunch of poopy-heads.<p>";
}
else
{
print $buffer;
}
?>
推荐答案
尽管代码中的页面( http://www.indiagoldrate.com/gold-rate-in-mumbai-today.htm )不是有效的DOM文档,您仍然可以使用PHP的 DOMDocument 。
例如,今天我们在孟买市获得1g 22k黄金的价格:
Though the page in your code (http://www.indiagoldrate.com/gold-rate-in-mumbai-today.htm) is not a valid DOM document, you still can parse it with PHP's DOMDocument. For example here we'll get the price of 1g 22k gold in Mumbay city today:
libxml_use_internal_errors(true); //get rid of the warnings
$dom = new DOMDocument;
$dom->loadHTML($buffer);
$xp = new DOMXPath($dom);
$price = $xp->query('//*[@id="right_center"]/table[1]/tr[3]/td[2]/table/tr[1]/td[2]')->item(0)->nodeValue;
libxml_clear_errors();
libxml_use_internal_errors(false);
var_dump($price);
这篇关于如何从网站获取值(在PHP中使用cUrl)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文