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

Exception or error:

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

How to solve:

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.

Answer:

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'];

Leave a Reply

Your email address will not be published. Required fields are marked *