php nested heredoc and escaping variables - php

I am using heredoc to create a php file which needs to use heredoc in the generated file as the file will create other files.
The <<<EOD bit works fine and I can see all the variables properly escaped.
The problem I'm having is the nested heredoc <<<EOL where \$languageStrings isn't escaped
If I use \$languageStrings and run the generated file ddd.php, the output is this:
<?php
= Array (
'LBL_LOCATION_INFORMATION' => 'Basic Information',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'SINGLE_' => ''
);
if i use \\$languageStrings trying to esacpe the backslash i get:
<?php
\ = Array (
'LBL_LOCATION_INFORMATION' => 'Basic Information',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'SINGLE_' => ''
);
How can I correct this so i get $languageStrings = Array (? I did think about trying to open the file and insert into a specific line but the file will always be different.
I'm open to suggestions
Here is an example of my heredoc
$text = <<<EOD
This is some text
This is some more text
This is a \$variable //outputs this is a $variable
This is some more text
EOD;
$text .= <<<EOD
\n
\$targetpath = 'modules/' . \$moduleInstance->name;
if (!is_file(\$targetpath)) {
mkdir(\$targetpath);
mkdir(\$targetpath . '/language');
// create the language file
\$languagepath = 'languages/en_us';
\$languageContents = <<<EOL
<?php
\$languageStrings = Array (
'LBL_LOCATION_INFORMATION' => 'Basic Information',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'SINGLE_\$moduleInstance->name' => '\$moduleInstance->name'
);
EOL;
file_put_contents(\$languagepath . '/' . \$module->name . '.php', \$languageContents);
}
EOD;
file_put_contents('ddd.php', $text);

I fixed it by creating a variable outside of the heredoc
$strings = '\$languageStrings';
and replacing \$languageStrings with $strings = Array ( in the heredoc string
The output is what I expected

Need a single quotes like Heredoc. This name is Nowdoc.
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.
$foo = "bar";
echo <<<STR
str $foo
STR;
echo <<<'STR'
str $foo
STR;
OR
echo "str $foo";
echo 'str $foo';
Expected Result:
->str bar
->str $foo
Since PHP 5.3.0, the opening Heredoc identifier may optionally be double quotes
<<<"FOO"
FOO;
same as
<<<FOO
FOO;
I prefer use every time double-quoted heredoc for intelligibility, although it is optional.
Doc says: php.net
Nowdocs are to single-quoted strings what heredocs are to
double-quoted strings. A nowdoc is specified similarly to a heredoc,
but no parsing is done inside a nowdoc. The construct is ideal for
embedding PHP code or other large blocks of text without the need for
escaping. It shares some features in common with the SGML construct, in that it declares a block of text which is not for
parsing.
A nowdoc is identified with the same <<< sequence used for heredocs,
but the identifier which follows is enclosed in single quotes, e.g.
<<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc
identifiers, especially those regarding the appearance of the closing
identifier.

Related

PHP: How to assign large string with single and double quotes

I need to assign large strings in an array. These strings contain single and double quotes as well as backslashes which cannot be escaped at first.
My code looks like:
$myArray = [
'x' => 'this_is_my_string',
];
Now instead of 'this_is_my_string' I have large strings as:
\relative c' {
\key ees \major
bes'2 \mf c bes4. (as8) g4 (as) \breathe
\bar "|."
How to write my code to directly assign large strings like this one?
I have tried with HEREDOC and NOWDOC and addslashes/addcslashed but they require to escape at least one of ´or ".
BTW: the large strings are Lilypond snippets
Simply use a nowdoc.
A nowdoc is specified similarly to a heredoc, but no parsing is done
inside a nowdoc. The construct is ideal for embedding PHP code or
other large blocks of text without the need for escaping.
<?php
$myArray = [
'x' => <<<'STR'
\relative c' {
\key ees \major
bes'2 \mf c bes4. (as8) g4 (as) \breathe
\bar "|."
STR
];
echo $myArray['x'];
You're looking for Output Buffering.
<?php
ob_start();
?>\relative c' {
\key ees \major
bes'2 \mf c bes4. (as8) g4 (as) \breathe
\bar "|."<?php
$myArray = [
'x' => ob_get_clean()
];
?>
ob_start() initialises output buffering, redirecting STDOUT to the buffer. ob_end_clean() will end output buffering, and return the buffer up to that point for use.

Generate & store unescaped strings in PHP

How can I generate and store a completely unescaped string in PHP?
In JS I can do it this way:
// Generates unescaped string
const unescaped = String.raw`\/pass\nfoo=`;
// Interacts with unescaped string without changing it
const pass = unescaped.concat(`i15`);
console.log(pass);
// -> \/pass\nfoo=i15
while without String.raw it'd work differently:
console.log(`\/pass\nfoo=`);
// 1. /pass
// 2. foo=
How could I achieve the same in PHP?
Seems like the manual doesn't mention this topic.
In general, you could just use single quoted strings:
$unescaped = '\/pass\nfoo=';
$unescaped .= 'i15';
echo $unescaped;
Output:
\/pass\nfoo=i15
However there are two exceptions to this, when you have \\ or \' in your string, both of which are treated as an escaped character i.e. \ or '. e.g.
$unescaped = '\/pa\\s\'s\nfoo=';
$unescaped .= 'i15';
echo $unescaped;
Output:
\/pa\s's\nfoo=i15
You can work around that limitation by using nowdoc syntax:
$unescaped = <<<'EOT'
\/pa\\s\'s\nfoo=
EOT;
$unescaped .= <<<'EOT'
i15
EOT;
echo $unescaped;
Output:
\/pa\\s\'s\nfoo=i15
Demo on 3v4l.org

Using multiple quotations in PHP codes

Let's say this is my script down here, as you can see I've used multiple " and '. These quotations conflict in ending the current php variable, so it basically sees this:
$message = "<?php echo '<div class="
As a string, whilst the quotation is only to define the class, not to end the variable. I've tried using ' but then it conflicts with the echo, so I'm kinda stuck at the moment.
<?php
$message = "
<?php
echo '<div class="gebruiker">';
$fh = fopen('_gebruiker.txt','r');
while ($line = fgets($fh)) {
echo($line);
}
fclose($fh);
echo '</div>';
?>
";
**MORE PHP CODE HERE**
?>
How can I use multiple quotations in one PHP script without them having conflicts.
If you use single quotes outside, you need to escape all single quotes inside, but can use double quotes and the dollar char without escaping.
If you use double quotes outside, you need to escape all double quotes and dollar chars inside, but can use single quotes without escaping.
If you use a heredoc string, you need to escape dollar chars but can use both single and double quotes without escaping.
If you use a nowdoc string, you do not need to escape anything unless you have FOO; in the string at the beginning of a new line.
So the solution is to use a nowdoc string:
$message = <<<'EOF'
your stuff with " or ' or $ here!
EOF;
Adding a backslash so PHP can recognize just only double quotes or quotes when escaped.
Example:
echo "<div class=\"gebruiker\">";
I suggest using either Heredoc or Nowdoc
Example
$foo = 'test';
// Heredoc
$here = <<<HERE
I'm here, $foo!
HERE;
// Nowdoc
$now = <<<'NOW'
I'm now, $foo!
NOW;
Heredoc will print the contents of $foo when echoed while Nowdoc will simply echo $foo.
In the references I added below you can do more reading up on this subject.
References:
php.net - strings
stackoverflow - advantages of heredoc vs nowdoc
You can escape the quotes with a slash character like so: \"
This should work, you can't open Php tag without closing before.
<?php
$message = '<div class="gebruiker">';
$fh = fopen('_gebruiker.txt','r');
while ($line = fgets($fh)) {
$message .=$line.'<br/>';
}
fclose($fh);
$message.='</div>';
echo $message;
**MORE PHP CODE HERE**
?>

PHP : Using single quotes and double quotes in single string

How can i use string like below code.
$str = 'Is yo"ur name O'reil"ly?';
The above code is just an example..I need to use big html template which contains single and double quotes.I tried Addslashes php method but when i use single and double quote string in that function i get syntax error.Please help me.
Note : my realtime usage is json data like below.
$string = "
<html>
...
<b:if cond='data:blog.pageType == "item"'>
..
";
$string = '{"method":"template","params":{"1":"'.$string.'"},"token":"12345"}';
You can use a heredoc for that:
$string = <<<EOM
<html>
...
<b:if cond='data:blog.pageType == "item"'>
..
EOM;
If you wish to prevent variable interpolation as well you can use nowdoc (since 5.3):
$string = <<<'EOM'
<html>
...
<b:if cond='data:blog.pageType == "item"'>
..
EOM;
Both heredoc and nowdoc have specific formatting requirements, so be sure to read the manual properly.
I used heredoc to do the same like
$string = <<< EOF
'Is yo"ur name O'reil"ly?'
EOF;
You can use heredoc like this:
$str = <<< EOF
'Is yo"ur name O'reil"ly?'
EOF;

PHP new line problem

simple problem baffling me...
i have a function:
function spitHTML() {
$html = '
<div>This is my title</div>\n
<div>This is a second div</div>';
return $html
}
echo $spitHTML();
Why is this actually spitting out the \n's?
Backslashes used in single quote strings do not work as escape characters (besides for the single quote itself).
$string1 = "\n"; // this is a newline
$string2 = '\n'; // this is a backslash followed by the letter n
$string3 = '\''; // this is a single quote
$string3 = "\""; // this is a double quote
So why use single quotes at all? The answer is simple: If you want to print, for example, HTML code, in which naturally there are a lot of double quotes, wrapping the string in single quotes is much more readable:
$html = '<div class="heading" style="align: center" id="content">';
This is far better than
$html = "<div class=\"heading\" style=\"align: center\" id=\"content\">";
Besides that, since PHP doesn't have to parse the single quote strings for variables and/or escaped characters, it processes these strings a bit faster.
Personally, I always use single quotes and attach newline characters from double quotes. This then looks like
$text = 'This is a standard text with non-processed $vars followed by a newline' . "\n";
But that's just a matter of taste :o)
Because you're using single quotes - change to double quotes and it will behave as you expect.
See the documentation for Single quoted strings.
Change ' to " :) (After that, all special chars and variable be noticed)
$html = "
<div>This is my title</div>\n
<div>This is a second div</div>";

Categories