用php从yahoo网页获取股票数据

过下准备写个股票机械交易系统,先搞掂数据采集这部分先,做了个用php从yahoo获取股票数据的例子, 运行在shell下,其实php做shell几好用的.

以下为源代码:

gupiao.php ,  获取600808马钢股份的数据.
——————————–

<?

include “Snoopy.class.inc”;

$url=”http://finance.cn.yahoo.com/q?s=600808.ss”;

$snoopy = new Snoopy;
$snoopy->agent = “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)”;
$snoopy->fetch($url);
$getstr=$snoopy->results;
$getstr=trim($getstr);

if($getstr==””)
{
print “No Data”;
print “\n”;
exit;
}

$str=mycut(“<span id=\”top_date\”>”,”<div class=\”ft\”>”,$getstr);
$pieces = explode(“</span>”, $str);
$ftime=$pieces[0];
$ftime=trim($ftime);
print “时间: “.$ftime;
print “\n”;

$stra=mycut(“最新价:”,”</”,$str);
$stra=$stra.”</”;
//print $stra;
$stra=mycut(“>”,”</”,$stra);
print “最新价: “.$stra;
print “\n”;

$strb=mycut(“今开盘:”,”</”,$str);
$strb=$strb.”</”;
$strb=mycut(“>”,”</”,$strb);
print “开盘价: “.$strb;
print “\n”;

$strc=mycut(“最高价:”,”</”,$str);
$strc=$strc.”</”;
$strc=mycut(“>”,”</”,$strc);
print “最高价: “.$strc;
print “\n”;

$strd=mycut(“最低价:”,”</li>”,$str);
$strd=mycut(“>”,”</”,$strd);
print “最低价: “.$strd;
print “\n”;

$stre=mycut(“前收盘:”,”</”,$str);
$stre=$stre.”</”;
$stre=mycut(“>”,”</”,$stre);
print “前收盘: “.$stre;
print “\n”;
function mycut($firststr,$laststr,$srcstr)
{
// $findstr=””;

$pos1 = strpos($srcstr, $firststr);

if ($pos1 === false)
{
return “”;
}

//print “pos1: “.$pos1.”\n”;
$pos2 = strpos($srcstr, $laststr, $pos1);

if ($pos2 === false)
{
return “”;
}

if ($pos2<$pos1)
{
return “”;
}

//print “pos2: “.$pos2.”\n”;
// $num=1;
$message=explode($firststr,$srcstr);
$message=explode($laststr,$message[1]);

return $message[0];
}

?>

还是用到php的Snoopy类, 在shell状态下输入php -q gupiao.php就可以执行,当然也可以运行在web下.

源代码下载,包含Snoopy类

关于无聊人

一个无聊人而已
此条目发表在php分类目录。将固定链接加入收藏夹。

用php从yahoo网页获取股票数据》有7条回应

  1. cai说:

    老大你这代码怎么运行呀。我是在本地wamp测试的。。

  2. 无聊人说:

    在php的shell方式可以,即在windows下用cmd,linux下在终端下,不过在放在web里也可以.

  3. cai说:

    为什么我看到网上只是出现:http://www.zinvest.cn/test/gupiao/gupiao.php
    时间: 最新价: 开盘价: 最高价: 最低价: 前收盘: 其它都没有

  4. 我换新域名了,换下新链接!

  5. 申请说:

    我是完美社区站长,申请友链.发到我邮箱.

  6. 无聊人说:

    没兴趣

  7. cai说:

    版主。。。。我的问题。。。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注