dongxianshuai8927
2015-09-25 11:37
浏览 255
已采纳

在嵌入php文件的html文件中插入一个变量

this code shows a set of html statements embedded in a php file. Here in the second line i want that reference (href) value to be a variable depending upon the loop value ($i). But when I click on the link it goes to $i.html instead of going to the value in $i. please help

echo '<li>
          <div class="imgholder">
             <a href= "$i.html">
                <img src="images/demo/imgl.png" alt="" />
             </a>
           </div>
           <div class="latestnews">
              <h2>Text 1</h2>
              <p>Text 2</p>
           </div>
           <br class="clear" />
      </li>'; 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douque9815 2015-09-25 11:42
    已采纳

    Try this

     echo "<li>
       <div class='imgholder'><a href= '$i.html'>
       <img src='images/demo/imgl.png' /></a></div>
            <div class='latestnews'>
              <h2>Text 1</h2>
              <p>Text 2</p>
             </div>
            <br class='clear' />
          </li>"
    
    已采纳该答案
    打赏 评论
  • duanqiao2006 2015-09-25 11:40

    There is concatenation operator ('.'), which returns the concatenation of its right and left arguments. Try with .:

    echo '<li>
           <div class="imgholder"><a href= "'. $i  .'.html">
           <img src="images/demo/imgl.png" alt="" /></a></div>
                <div class="latestnews">
                  <h2>Text 1</h2>
                  <p>Text 2</p>
                 </div>
                <br class="clear" />
              </li>'; 
    
    打赏 评论
  • dongwuwan5646 2015-09-25 11:40

    Try with

    echo '<li>
           <div class="imgholder"><a href= "'.$i.'.html">
           <img src="images/demo/imgl.png" alt="" /></a></div>
                <div class="latestnews">
                  <h2>Text 1</h2>
                  <p>Text 2</p>
                 </div>
                <br class="clear" />
              </li>'; 
    

    You have to concatenate the PHP variable with the HTML tags. You got href as $i.html as the value of the variable was not substituted correctly.

    打赏 评论
  • duanbai1974 2015-09-25 11:45

    How about you make it like this:

    <?php for($i = 0; $i<10; $i++){ ?>
    <li>
        <div class="imgholder">
            <a href="<?php echo $i; ?>.html"> <img src="images/demo/imgl.png" alt="" /></a>
        </div>
        <div class="latestnews">
            <h2>Text 1</h2>
            <p>Text 2</p>
        </div> <br class="clear" />
    </li>
    <?php } ?> 
    

    In this context you have $i is a static String. But you want to have a variable which is dynamically changing.

    Edited: Something like this is what I used to do, but it is not "clean" php.

    打赏 评论
  • dslkchyv673627 2015-09-25 11:48

    use double quotes or concatenation, as mentioned before.

    But I'd like to recomend you to take a look on templates like smarty or twig, or even plain php

    打赏 评论

相关推荐 更多相似问题