2

可能重复:
获取 A 元素的 href 属性

如何从此代码中提取sessionId和变量?viewstate

代码是这样的:

$url = "http://www.atb.bergamo.it/ITA/Default.aspx?SEZ=2&PAG=38&MOD=LINTRV";

$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec ($ch);
curl_close($ch);

preg_match('~<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />~',$html,$viewstate);

var_dump(file_get_contents($ckfile)); //<--- There's the sessionId variable in it
var_dump($viewstate[1]);              //<--- View State

你能帮我吗?

4

1 回答 1

4

没有正则表达式,您可以非常简单地做到这一点:

$viewstate = explode('id="__VIEWSTATE" value="', $html);
$viewstate = explode('"', $viewstate[1]);
$viewstate = $viewstate[0];

cookie 也一样:

$sesid = explode('SessionId', file_get_contents($ckfile));
$sesid = explode('\n', $sesid[1]);
$sesid = trim($sesid[0]);

把它们放在一起,你得到

   $url = "http://www.atb.bergamo.it/ITA/Default.aspx?SEZ=2&PAG=38&MOD=LINTRV";    
   $ckfile = tempnam ("/tmp", "CURLCOOKIE");
   $ch = curl_init ($url);
   curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
   curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
   $html = curl_exec ($ch);
   curl_close($ch);

    $viewstate = explode('id="__VIEWSTATE" value="', $html);
    $viewstate = explode('"', $viewstate[1]);
    $viewstate = $viewstate[0];    

    $sesid = explode('_SessionId', file_get_contents($ckfile));
    $sesid = explode("\n", $sesid[1]);    
    $sesid = trim($sesid[0]);

    echo $viewstate."<br/>";
    echo $sesid;

适用于我的测试设置。

于 2012-12-01T19:41:30.853 回答