du1462 2013-01-15 16:28
浏览 31
已采纳

在每次执行脚本时存储变量值 - PHP

I have this code:

$filename = 'files.xml';
$dom = new DomDocument();

$dom->load($filename);

$oldCount = '';

$newCount = $dom->getElementsByTagName('file')->length;

if($newCount == $oldCount){
echo "There are no new elements in the XML.
";
}

else {
 echo "New Count is: ".$newCount."
";
 echo "Old Count is: ".$oldCount."
";

for ($oldCount =0; $oldCount < $newCount; $oldCount++){
    $file = file_get_contents('files.xml');
    $xml = simplexml_load_string($file); 

    $result = $xml->xpath('file');
    echo "File ".($oldCount+1).": ".$result[$oldCount]."

";
    //echo "Old: ".$oldCount."
";
    //echo "New: ".$newCount."
";
   }
   $oldCount = $newCount;
   //echo "Old Count at the end: ".$oldCount."
";
}
echo "Old Count at the end: ".$oldCount."
";

What I want to do is ensure that the value of $oldCount is stored at the end such that, if files.xml has the same number of elements inside the , it would display - "There are no new elements in the XML" when the program is run the second time around.

For test purpose, I have 2 elements in my xml, meaning my xml looks like:

<?xml version="1.0"?>
<files>
  <file>.DS_Store</file>
  <file>ID2PDF_log_2.xml</file>
</files>

So, if I run my test.php with only these 2 elements, it should display the info first time. But, the second time I run it, it should display the message. It's pretty obvious I am weak at variable scope in PHP. How can I do this?

  • 写回答

1条回答 默认 最新

  • dongsong73032 2013-01-15 16:51
    关注

    Command line doesn't support sessions without workarounds, since sessions generally depend on cookies (which don't exist in the command-line) or passing around url query parameters.

    Instead, just dump your number out to a file, e.g.

    file_put_contents('count.txt', $count);
    

    then read it in later, e.g.

    $count = file_get_contents('count.txt');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?