3

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

Nick Price
  • 953
  • 2
  • 12
  • 26

5 Answers5

3

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;
t.h3ads
  • 1,858
  • 9
  • 17
3

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?

Community
  • 1
  • 1
Pepo_rasta
  • 2,842
  • 12
  • 20
3

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");
?>
Loic
  • 90
  • 6
2

try to change,

$templateProcessor->saveAs(dirname(__FILE__) . '../../templates/doc1.docx');

to

$templateProcessor->saveAs($_SERVER['DOCUMENT_ROOT'] . '/templates/doc1.docx');
1

You can siomply avoid the escaping by using a double slash

$templateProcessor->
saveAs('C:\xampp\htdocs\portal\templates\\' . $this->fileName . '.docx');
Aruna Tebel
  • 1,436
  • 1
  • 12
  • 24