繁体   English   中英

PHP 多行字符串与 PHP

[英]PHP multiline string with PHP

我需要回应很多 PHP 和 HTML。

我已经尝试过显而易见的,但它不起作用:

<?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 }  ?>';
?>

我该怎么做?

您不需要输出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>';
?>

您不能在这样的字符串中运行 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;

使用 Heredocs 输出包含变量的多行字符串。 语法是...

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

“HEREDOC”部分就像引号一样,可以是您想要的任何内容。 结束标记必须是它所在行上的唯一内容,即前后没有空格,并且必须以冒号结尾。 有关更多信息, 请查看手册

使用冒号表示法

另一种选择是将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>

代码中的内部单引号集正在杀死字符串。 每当您点击单引号时,它就会结束字符串并继续处理。 你会想要这样的东西:

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

为此,您必须删除字符串中的所有'字符或使用转义字符。 像:

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

使用show_source(); PHP的功能。 查看show_source 中的更多详细信息。 我想这是一个更好的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM