Use PHP's nowdoc feature (emphasis mine):
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.
Example
<?php
$test_var = 1;
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
$test_var
EOD;
echo $str;
Outputs
Example of string
spanning multiple lines
using nowdoc syntax.
$test_var
So this ...
<a href="
<?php
$fh = fopen($p['n'].'.php', 'w') or die("Can't create file");
if($fh)
{
$code = <<<'EOD'
<?php
// html and php combined code (the php is for sessions)
?>"
EOD;
echo fwrite($file,$code);
fclose($file);
}?>"></a>
... should work for you.