2017-06-18 103 views
0

我有一個非常簡單的PHP腳本,它接受XML的值並將其保存在$ _SESSION中。但是,當頁面被更改並且我想要檢索這些值時,它們是空的。下面是所採用的值的方法:PHP - 會話不存儲變量值

session_start(); 
if (isset($_REQUEST["LocalitatForm"])) { 
recollirDades(); 
} 

function recollirDades(){ 
    $localitat = $_REQUEST["localitat"]; 
    $data = $_REQUEST["data"]; 
    $min = 0; 
    date_format($data, 'Y-m-d'); 
    $xmlDoc = simplexml_load_file("../data/".$localitat.".xml"); 
    foreach ($xmlDoc->prediccion->dia as $dia){  
     if($dia['fecha'] == $data){ 
      $min = $dia->temperatura->minima; 
      $max = $dia->temperatura->maxima; 
     } 
    } 

    $_SESSION["localitat"] = $localitat; 
    $_SESSION["data"] = $data; 
    $_SESSION["min"] = $min; 
    $_SESSION["max"] = $max; 
    header("location: ../views/Temperatura.php"); 
} 

,這裏是應該顯示值DOC(「Temperatura.php」):

<?php 
session_start(); 
echo $_SESSION["localitat"]." ". $_SESSION["data"] . " " .   
$_SESSION["min"]; 
$localitat = $_SESSION["localitat"]; 
$data = $_SESSION["data"]; 
$min = $_SESSION["min"]; 
$max = $_SESSION["max"]; 
?> 
<html> 
<head> 
    <title>Temperatura</title> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
</head> 
<body> 
     <div id='data'> 
     Localitat: <?php echo ucfirst($localitat)?><br> 
     Data: <?php echo $data ?><br> 
     Temperatura mínima: <?php echo $min ?>ºC<br> 
     Temperatura màxima: <?php echo $max ?>ºC<br> 
    </div> 
    <a href='../index.php'><input type='button' value='Tornar a buscar'>   
    </a> 

</body> 
</html> 

在第一個文件,該值是正確的,我用回聲查了一下。

+0

你什麼時候調用'recollirDades()'?因爲我看不到它被調用的地方。 – Jonathan

+0

對不起,忘了把方法調用放在腳本的開頭 –

+0

你在日誌文件中看不到任何錯誤嗎? – CoderSam

回答

0

好的,我發現了這個問題。您不能立即在$ _SESSION中存儲XML節點的值。在這種情況下,我把它作爲字符串。所以該方法的代碼將是這樣的:

session_start(); 
if (isset($_REQUEST["LocalitatForm"])) { 
recollirDades(); 
} 

function recollirDades(){ 
$localitat = $_REQUEST["localitat"]; 
$data = $_REQUEST["data"]; 
$min = 0; 
date_format($data, 'Y-m-d'); 
$xmlDoc = simplexml_load_file("../data/".$localitat.".xml"); 
foreach ($xmlDoc->prediccion->dia as $dia){  
    if($dia['fecha'] == $data){ 
     $min = (string)$dia->temperatura->minima; 
     $max = (string)$dia->temperatura->maxima; 
    } 
} 

$_SESSION["localitat"] = $localitat; 
$_SESSION["data"] = $data; 
$_SESSION["min"] = $min; 
$_SESSION["max"] = $max; 
header("location: ../views/Temperatura.php"); 
}