Home Insert php and html into div in php variable
Reply: 2

Insert php and html into div in php variable

patrice
1#
patrice Published in 2018-01-13 00:53:02Z

I have a php variable as such:

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

I want the code below inside the "marker" div that's within the above var:

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

The <<<EOD method isn't working and going in/out of php tags doesn't seem to work. It seems like it's going to look messy, I wondering what is the syntax I'm missing here?

Lawrence Cherone
2#
Lawrence Cherone Reply to 2018-01-13 01:07:09Z

Try this:

<?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>';
aendeerei
3#
aendeerei Reply to 2018-01-13 01:49:43Z
  • Activate error reporting for showing eventual errors.
  • Make use of the PHP's sprintf() function to build your final result in an elegant manner.
  • Echo the output as usual, or by using the heredoc syntax: <<<. In the case of the latter I am wondering why would you choose to do it?

Notice the use of the curly brackets { and } inside the heredoc output. See this answer and Example #3 Heredoc string quoting example in the heredoc syntax.

Good luck.

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

Output (visible with "View page source" in browser, or similar option):

<div class="marker" data-lat="50.2341234">
    <p>Some address</p>
    <p>Some description value</p>
</div>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.449411 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO