在php变量中将php和html插入div中

时间:2018-01-13 00:53:02

标签: php wordpress

我有一个php变量:

$output_map[$the_ID]['map'] = '<div class="marker" data-lat="'.$get_google_map['lat'].'"></div>';

我希望下面的代码位于上面var:

中的“marker”div内
<p><?php echo $location['address']; ?></p>
<p><?php the_field('description'); ?></p>

<<<EOD方法不起作用,进入/退出php标签似乎不起作用。看起来它看起来很混乱,我想知道我在这里缺少什么语法?

2 个答案:

答案 0 :(得分:0)

试试这个:

<?php
$output_map[$the_ID]['map'] = '
<div class="marker" data-lat="'.$get_google_map['lat'].'">
    <p>'.$location['address'].'</p>
    <p>'.get_field('description').'</p>
</div>';

答案 1 :(得分:0)

  • 激活错误报告以显示最终错误。
  • 利用PHP的sprintf()函数以优雅的方式构建最终结果。
  • 照常回放输出,或使用heredoc syntax: <<<。在后者的情况下,我想知道你为什么选择这样做?

注意在heredoc输出中使用大括号{}。请参阅this answer中的heredoc syntax示例#3 Heredoc字符串引用示例

祝你好运。

<?php

// Display eventual errors and exceptions.
error_reporting(E_ALL);
ini_set('display_errors', 1); // SET IT TO 0 ON A LIVE SERVER!

// Dummy test function
function the_field($name) {
    return 'Some ' . $name . ' value';
}

// Dummy test values.
$the_ID = 1;
$get_google_map['lat'] = '50.2341234';
$location['address'] = 'Some address';

// Build the map item's content.
$output_map[$the_ID]['map'] = sprintf(
        '<div class="marker" data-lat="%s">
            <p>%s</p>
            <p>%s</p>
        </div>'
        , $get_google_map['lat']
        , $location['address']
        , the_field('description')
);

// Option 1.
//echo $output_map[$the_ID]['map'];

// ... or Option 2.
echo <<<MAP
    {$output_map[$the_ID]['map']}
MAP;

输出(在浏览器中显示“查看页面源”或类似选项):

<div class="marker" data-lat="50.2341234">
    <p>Some address</p>
    <p>Some description value</p>
</div>
相关问题