2015-04-01 33 views
0

我想從當前頁面獲取節點值,並將其傳遞到URL的參數後,用戶重定向到另一個頁面獲取節點值後,這裏是我的代碼:PHP - 重定向到另一頁從當前頁

<?php 

    $dom = new DOMDocument; 
    $html = file_get_contents(home_url(). $_SERVER['REQUEST_URI']); 
    $dom->loadHTML($html); 

    $addresses = $dom->getElementsByTagName('address'); 


    foreach ($addresses as $key => $address) { 
      $add[$key] = $address->nodeValue; 
    } 


    $fields['address'] = urlencode($add[0]); 

    $qry = http_build_query($fields); 

    if(!empty($qry)){ 
     header('Location: http://example.com/subscription-form/?' . $qry) ; 
     } 

     ?> 

它確實重定向成功,但http_build_query值爲空。以下是一個重定向示例:http://example.com/subscription-form/?address=,該URL沒有值$_GET['address']

+0

也許'$ add [0]'沒有設置。用'var_dump($ add);嘗試一下調試。 die();'在'foreach'循環後面' – d79 2015-04-02 00:26:47

+0

@ d79 $ add [0]被設置,並且還有幾個變量我沒有被包含在這個代碼中以避免冗長的代碼;也被設置。 – 2015-04-02 00:38:14

+0

嘗試在重定向後添加'exit;'([源](http://stackoverflow.com/questions/4702149/php-redirect-with-http-query-string-variables#4702187)) – d79 2015-04-02 13:41:53

回答

0

PHP重定向沒有工作,所以我用JavaScript嘗試過了,它的工作:

$redir = '<script type="text/javascript">'; 
    $redir.= 'window.location.href="http://example.com/subscription-form/?'; 
    $redir.= $qry .'"'; 
    $redir.= '</script>'; 

    echo $redir; 

,是的,沒有必要urlencode因爲它已經被http_build_query完成。