2012-12-01 55 views
2

可能重複:
Grabbing the href attribute of an A element如何從此代碼獲取sessionId和viewstate變量?

我怎樣才能提取此代碼sessionIdviewstate變量?

的代碼是這樣的:

$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 

你能幫助我嗎?

+0

使用HTML解析器來提取比正則表達式更容易。然而,對於正則表達式,之前已經提出並回答了這個問題。 – hakre

回答

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; 

廠建立。

+0

非常感謝你! :) – nhDeveloper

相關問題