dongzhuji1042 2012-10-31 14:37
浏览 49
已采纳

PHP表单提交和解析

I am looking to use PHP to get a few random paragraphs from this site: http://watchout4snakes.com/CreativityTools/RandomParagraph/RandomParagraph.aspx

What's the shortest set of code to initiate the Submit button (don't need to fill in the text fields) and parse out only the resultant random text?

Can't seem to get the submit piece to work.

  • 写回答

2条回答 默认 最新

  • douliangpo0128 2012-10-31 16:08
    关注

    More flexible way - fetch viewstate and eventvalidation dynamically:

    <?php
    $url = 'http://watchout4snakes.com/CreativityTools/RandomParagraph/RandomParagraph.aspx';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)'); 
    $c = curl_exec($ch); 
    curl_close($ch); 
    
    //__VIEWSTATE
    $viewstate = '';
    
    //__EVENTVALIDATION
    $eventvalidation = '';
    
    // Fetch VIEWSTATE
    $p1 = '<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="';
    $p = strpos($c, $p1);
    if ($p !== false) {
        $s = substr($c, $p+strlen($p1));
        $pcs = explode('"', $s);
        if (!empty($pcs[0])) {
            $viewstate = $pcs[0];
        }
    }
    
    // Fetch EVENTVALIDATION
    $p1 = '<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="';
    $p = strpos($c, $p1);
    if ($p !== false) {
        $s = substr($c, $p+strlen($p1));
        $pcs = explode('"', $s);
        if (!empty($pcs[0])) {
            $eventvalidation = $pcs[0];
        }
    }
    
    // PUT YOUR OBJECT & SUBJECT HERE
    $postvalues = array(
        'tmpl$main$txtSubject' => '',
        'tmpl$main$txtObject' => '',
        'tmpl$main$btnNew' => 'New Paragraph',
    );
    
    $url = 'http://watchout4snakes.com/CreativityTools/RandomParagraph/RandomParagraph.aspx?__VIEWSTATE='.urlencode($viewstate).'&__EVENTVALIDATION='.urlencode($eventvalidation).'&tmpl%24main%24txtSubject='.urlencode($postalues['tmpl$main$txtSubject']).'&tmpl%24main%24txtObject='.urlencode($postalues['tmpl$main$txtObject']).'&tmpl%24main%24btnNew=New%20Paragraph';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)'); 
    $c = curl_exec($ch); 
    curl_close($ch); 
    
    
    $t = '<span id="tmpl_main_lblPara" class="randomSentence">';
    $p = strpos($c, $t);
    if ($p !== false) {
        $s = substr($c, $p + strlen($t));
        $pcs = explode('</span>', $s);
    
    
       echo $pcs[0]; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?