0

Say I have

$output = '';

and I want to include the following code within the double ''.

<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
    <a href="?route=common/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
    <a href="?route=subscribers/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>

How could I go about doing this?

5
  • I see what you're trying to do...but why? Can you just use an include instead? Commented Jul 1, 2013 at 22:19
  • Add the HTML part inside an echo or inside a print. Commented Jul 1, 2013 at 22:19
  • Do you want to include the literal php string out the results of those PHP values? Commented Jul 1, 2013 at 22:19
  • look at templateing, Mustache is good Commented Jul 1, 2013 at 22:19
  • You could do a simple <?= $output ?> Commented Jul 1, 2013 at 22:19

2 Answers 2

2

You could use output buffering, something like this:

<?php ob_start();?>

<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
    <a href="?route=common/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
    <a href="?route=subscribers/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>

<?php
    $output = ob_get_contents();
    ob_end_clean();  
?>

See In Action

Using this method of starting a buffer and then assigning the result to a variable is very handy and is used in some MVC frameworks.

Simple example:

<?php
/* Assign an array of values that will be passed 
 * to the loader then extracted into local variables */
$data['logged']=true;
$output = loadContentView('top_nav', $data);


function loadContentView($view, $data=null){
    $path = SITE_ROOT.'/path/to/views/'.$view.'.php';

    if (file_exists($path) === false){
        return('<span style="color:red">Content view not found: '.$path.'</span>');
    }
    /* Extract $data passed to this function */
    if($data != null){
        extract($data);
    }
    ob_start();
    require($path);
    $return = ob_get_contents();
    ob_end_clean();
    return $return;
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

I just changed my code to this instead... much easier

Thanks everyone for all the help!

<?php

if (!$this->customer->isLogged()) {
$output = '<ul class="nav megamenu"><li class="home"><a href="?route=subscribers/home"><span class="menu-title">Home</span></a></li>';
}else{
$output = '<ul class="nav megamenu"><li class="home"><a href="?route=common/home"><span class="menu-title">Home</span></a></li>';
}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.