質問

So I need to create a dynamic text file based on the name of a variable in php (ex: dynamicName.txt). I then need to write other variables in the file.

$testVar = "test.txt";

function sendCalc(){
    global $testVar;
    $objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$testVar");
    $fp = fopen($objCalcTxt, 'x');
    fwrite($fp, "Test\n");
    fclose($fp);

When I do the above, the file is created with no problem, and all the data is written successfully. However, this is not a dynamic file name.

$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc(){
    global $objName;
    global $ext;
    global $dynamicNameTxt;
    $objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
    $fp = fopen($objCalcTxt, 'x');
    fwrite($fp, "Test\n");
    fclose($fp);

When I try to concatenate the variable that contains the dynamic file name ($objName), with the $ext var, it does not want to create the file.

I echoed the $dynamicName var and it returns dynamicName.txt, so why doesn't this work with fopen. Essentially it has to be a problem with the concatenation right? If so, can I either concatenate a different way, or use a different method to open/create the file?

All help/ideas are appreciated.

役に立ちましたか?

解決

I do not really know what you're trying to achieve with the line

$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");

if from what i understand it should just be a string:

$objCalcTxt = "C:\\xampp\\htdocs\\test.new\\upload\\".$dynamicNameTxt;

Also I'd suggest you provide the needed variables as arguments for the function insted of using globals

function sendCalc($objName, $ext, $dynamicNameTxt){
...
}

他のヒント

You are declaring the global variables inside your function. This could destroy their initial values. Instead of using global variables in your function, rather pass the variables as arguments:

$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc(objName, $ext, $dynamicNameTxt)
{
    $objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
    $fp = fopen($objCalcTxt, 'x');
    fwrite($fp, "Test\n");
    fclose($fp);
}

Your other option is to specifically call the global variable:

global $objName;
global $ext;
global $dynamicNameTxt;
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc()
{
    $objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\".$GLOBAL['dynamicNameTxt']);
    $fp = fopen($objCalcTxt, 'x');
    fwrite($fp, "Test\n");
    fclose($fp);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top