PHP存储来自循环的所有变量以便稍后使用它们

时间:2015-04-01 11:21:22

标签: php arrays variables

我正在尝试使用一些WSDL webservice来处理每个参数。这工作绝对正常;但是,一旦脚本执行完毕,我想要#34; log"通过电子邮件发送给我

当我在循环中使用PRINTECHO时,一切正常(这将显示循环中不同变量的所有值)。但是,在循环之外,这只会显示一个变量。

有没有办法将所有变量存储到循环内部的数组中,以便以后可以在循环外使用,例如通过电子邮件发送?

这就是我的尝试:

<?php

// API request and response 
$requestParams = array(
  'Request' => 'Hello'
);

$client = new SoapClient('https://example.com/webservice.asmx?WSDL');
$response = $client->Command($requestParams);

//Load response as XML
$xml  = simplexml_load_string($response);
$rows = $xml->children('rs', TRUE)->data->children('z', TRUE)->row;

foreach ($rows as $row) {
$attributes = $row->attributes();

/* XML document contains two columns, first with attribute TO, 
   second with attribute Ref. This will extract required data  */

$To = (string) $attributes->To;  
$Ref= (string) $attributes->Ref;

// Here are few more lines in code to do some other work with each variable 

// All works absolutely fine until this line

/* I would liket to store all variables so I can use them to email 
   them as a log in one email */

$ToLog .= "<br>$To</br>";
$RefLog .="<br>$Ref</br>";
}

$to      = "nobody@example.com";
$subject = "Script successfully executed";

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$message = $ToLog . $RefLog

mail($to, $subject, $message, $headers);

?>

3 个答案:

答案 0 :(得分:1)

试试这个

$values = array();
foreach ($rows as $row) {
    $values[] = $row->attributes(); //stores the each values to the array
}

print_r($values);

答案 1 :(得分:1)

I think u just need to define both variable before starting the loop, like
$ToLog = "";
$RefLog = "";

Then if you can put whatever in this variable in side the loop you will get it after the loop, You do not need to take an array. 

不需要采取数组。

答案 2 :(得分:0)

尝试这样的事情

$finalArray = array();
foreach($rows as $row)
{
   $finalArray[] = $row["someIndex"];
}

然后finalArray应该包含来自foreach的所有变量:)