2012-09-21 141 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標籤:

<?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>'; 
?> 
+1

對我很好 - 謝謝 – Matt

28

你不能在這樣的字符串中運行PHP代碼。它只是不起作用。另外,當您退出PHP代碼(?>)時,PHP塊之外的任何文本都將被視爲輸出,因此不需要echo語句。

如果你需要做的與PHP代碼塊多輸出,可以考慮使用HEREDOC

<?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; 
0

的代碼中的內部單引號組正在殺死字符串。只要你點擊一個單引號就會結束字符串並繼續處理。你需要這樣的東西:

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

使用Heredocs輸出包含變量的多行字符串。語法是...

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

「HEREDOC」部分就像引號,可以是任何你想要的。結束標記必須是唯一的行,即在前或後沒有空格,並且必須以冒號結尾。欲瞭解更多信息check out the manual

1

爲此,您必須刪除字符串中的所有'字符或使用轉義字符。像:

<?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>