Reputation: 963
I am calling a function which is passed a string like below
$templateProcessor->saveAs('C:\xampp\htdocs\portal\templates\doc1.docx');
Problem is, I need it to be more like
$templateProcessor->saveAs('C:\xampp\htdocs\portal\templates\' . $this->fileName . '.docx');
If I do this however, my string breaks and I think it is due to the backslashes in the string.
How can I resolve this?
p.s. I actually would prefer to do something like this
$templateProcessor->saveAs(dirname(__FILE__) . '../../templates/doc1.docx');
but it didnt seem to like me using ../../ because I need to step out of the current working directory.
Thanks
Upvotes: 3
Views: 654
Reputation: 2900
only last backslash need to be escaped
$templateProcessor->saveAs('C:\xampp\htdocs\portal\templates\\' . $this->fileName . '.docx');
because with single quotes are recognized only \\
and \'
, single backslash is interpreted as character - so you were escaping single quote
look at this answer In PHP do i need to escape backslashes?
Upvotes: 3
Reputation: 90
The best way to build paths is probably to use the DIRECTORY_SEPARATOR
constant since it adapts to the OS you are using :
$path = implode(DIRECTORY_SEPARATOR, array('C:','xampp','htdocs','portal','templates',$this.filename.'.docx'));
$templateProcessor->saveAs($path);
Then you should also put your path in a config file in case you need to edit it some day.
In PHP 5.6 you can make a variadic function.
<?php
/**
* Builds a file path with the appropriate directory separator.
* @param string $segments,... unlimited number of path segments
* @return string Path
*/
function file_build_path(...$segments) {
return join(DIRECTORY_SEPARATOR, $segments);
}
file_build_path("home", "alice", "Documents", "example.txt");
?>
In earlier PHP versions you can use func_get_args.
<?php
function file_build_path() {
return join(DIRECTORY_SEPARATOR, func_get_args($segments));
}
file_build_path("home", "alice", "Documents", "example.txt");
?>
Upvotes: 3
Reputation: 1466
You can siomply avoid the escaping by using a double slash
$templateProcessor->
saveAs('C:\xampp\htdocs\portal\templates\\' . $this->fileName . '.docx');
Upvotes: 1
Reputation:
try to change,
$templateProcessor->saveAs(dirname(__FILE__) . '../../templates/doc1.docx');
to
$templateProcessor->saveAs($_SERVER['DOCUMENT_ROOT'] . '/templates/doc1.docx');
Upvotes: 2
Reputation: 1878
To escape the backslashes just place an additional backslash before them.
$fileName = 'file';
$path = 'C:\\xampp\\htdocs\\portal\\templates\\' . $fileName . '.docx';
print $path;
To make dirname
work, you might just need an additional slash:
$path = dirname(__FILE__) . '/../../templates/doc1.docx';
print $path;
Upvotes: 3