繁体   English   中英

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

[英]Insert php and html into div in php variable

我有这样的php变量:

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

我想要下面的代码在上面的var内的“标记” div中:

<p><?php echo $location['address']; ?></p>
<p><?php the_field('description'); ?></p>

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

尝试这个:

<?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>';
  • 激活错误报告以显示最终错误。
  • 利用PHP的sprintf()函数以一种优雅的方式构建最终结果。
  • 照常回显输出,或使用heredoc语法:<<< 对于后者,我想知道为什么您会选择这样做?

请注意,heredoc输出中使用了大括号{} 请参阅此答案Heredoc 语法中的Example#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>

暂无
暂无

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

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