2012-09-21 13 views
21

多くのPHPおよびHTMLをエコーする必要があります。PHPを使用したPHPの複数行の文字列

私はすでに明白なことをしようとしたが、それは働いていない:

<?php echo ' 
<?php if (has_post_thumbnail()) { ?> 
     <div class="gridly-image"><a href="<?php the_permalink() ?>"><?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false)));?></a> 
     </div> 
     <?php } ?> 

     <div class="date"> 
     <span class="day"> 
     <?php the_time('d') ?></span> 
     <div class="holder"> 
     <span class="month"> 
      <?php the_time('M') ?></span> 
     <span class="year"> 
      <?php the_time('Y') ?></span> 
     </div> 
    </div> 
    <?php } ?>'; 
?> 

私はそれをどのように行うことができますか?

+4

あなたは文字通り、PHPコードをエコーし​​ようとしていますか? –

+0

エスケープされていない引用符の明白な問題以外にも、あなたはすべて< and >タグを対応するhtmlコードに変換する必要があります< > – transilvlad

+1

この質問をするほとんどの人はHEREDOCを探しています。その答えを受け入れることができます。 – Archonic

答えて

20

あなたは出力にphpタグは必要ありません。あなたのコード内の一重引用符の内部セットが文字列を強制終了しています。一重引用符を押すたびに、文字列が終了し、処理が続行されます。

$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run'; 
+1

私によく見える - ありがとう – Matt

28

PHPコードをそのような文字列内で実行することはできません。それだけでは機能しません。同様に、PHPコード(?>)の「外」にあるときは、PHPブロック外のテキストはとにかく出力と見なされるため、echo文は必要ありません。

あなたがHEREDOCを使用することを検討して、PHPコードの塊とから複数行の出力を行うために必要がある場合:

<?php 
    if (has_post_thumbnail()) 
    { 
     echo '<div class="gridly-image"><a href="'. the_permalink() .'">'. the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false))) .'</a></div>'; 
    } 

    echo '<div class="date"> 
       <span class="day">'. the_time('d') .'</span> 
       <div class="holder"> 
       <span class="month">'. the_time('M') .'</span> 
       <span class="year">'. the_time('Y') .'</span> 
       </div> 
      </div>'; 
?> 
0

<?php 

$var = 'Howdy'; 

echo <<<EOL 
This is output 
And this is a new line 
blah blah blah and this following $var will actually say Howdy as well 

and now the output ends 
EOL; 
15

変数を含むマルチライン文字列を出力するには、Heredocsを使用します。構文は...

$string = <<<HEREDOC 
    string stuff here 
HEREDOC; 

「HEREDOC」部分は引用符と似ていて、任意のものを指定できます。終了タグは、その行の唯一のものでなければなりません。つまり、前後の空白がなく、コロンで終わらなければなりません。詳細はcheck out the manualをご覧ください。

1

これを行うには、文字列内のすべての'文字を削除するか、エスケープ文字を使用する必要があります。 Like:

<?php 
    echo '<?php 
       echo \'hello world\'; 
      ?>'; 
?> 
0

PHPのshow_source();機能を使用してください。詳細はshow_sourceで確認してください。これは私が推測するより良い方法です。

0

別のオプションは、コロンとif、代わりにブラケットのendifを使用することです:

<?php if (has_post_thumbnail()): ?> 
    <div class="gridly-image"> 
     <a href="<?php the_permalink(); ?>"> 
     <?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false))); ?> 
     </a> 
    </div> 
<?php endif; ?> 

<div class="date"> 
    <span class="day"><?php the_time('d'); ?></span> 
    <div class="holder"> 
     <span class="month"><?php the_time('M'); ?></span> 
     <span class="year"><?php the_time('Y'); ?></span> 
    </div> 
</div> 
関連する問題