2015-06-26 70 views
-2

我有一個.php頁面,裏面有很多HTML部分。 我正在運行一個FOR循環和FOR循環中的每個值,我想在循環內部的錨標記中傳遞一個PHP變量。HTML/PHP:我們如何將PHP變量插入到html的錨標記中?

我已經試過這樣:

for($i =0; $i<5 ; $i++) 
{ 
<a href = "Test.html?ID= <?php $i ?> > Sample text </a> 
} 

但它無法正常工作。

+0

的語法是什麼?這是JS還是PHP?如果是PHP,缺少echo –

+0

@ Fred-ii-它的PHP。 –

+0

那麼你不使用「回聲」。只需將純HTML注入到PHP中,並且缺少引號。 –

回答

1

任意數量的方式被納入echo。關鍵是不要將HTML與PHP混合,將它們分開分析。事情是這樣的:

for($i =0; $i<5 ; $i++) 
{ 
    echo '<a href="Test.html?ID=' . $i . '"> Sample text </a>'; 
} 

(在這個例子中所有的代碼是PHP和HTML是一個字符串,是echo -ed到輸出。)

或者這樣:

for($i =0; $i<5 ; $i++) 
{ 
?> 
    <a href="Test.html?ID=<?php echo $i; ?>"> Sample text </a> 
<?php 
} 

(在此示例中,PHP代碼包裹在<?php ?>標記中,並且HTML保留在這些標記之外)。

只要您將PHP代碼保存在<?php ?>標籤和HTML中的標籤,解析器會知道它們的區別。

1

你的語法是錯誤的,你不輸出任何東西,將其替換爲:

for($i =0; $i<5 ; $i++) 
{ 
    echo '<a href="Test.html?ID='.$i.'>Sample text</a>'; 
} 
1

HTML是否已到,而使用PHP

<?php 
    for($i =0; $i<5 ; $i++) 
    { 
     echo '<a href="Test.html?ID='.$i.'>Sample text</a>'; 
    } 
    ?> 
1
for($i =0; $i<5 ; $i++) 
{ 
     <a href = "Test.html?ID= <?php $i ?> > Sample text </a> 
} 

如果上面的代碼是你試過的代碼,它的格式不正確! 你在php中運行循環!所以你不能把html標籤直接放在php文件中! 使用echo來顯示html標籤!

for($i=0; $i<5; $i++) 
{ 
     echo "<a href=test.html?id=$i>Click here</a>"; 

} 

希望它有幫助!

0

試試這個。

for($i=0; $i<5; $i++) 
{ 
    echo "<a href=\"Test.html?id='.$i.'\">Click here</a>"; 
} 
0
for($i =0; $i<5 ; $i++) 
{ 
?> 
<a href="Test.html?ID=<?php echo $i; ?>"> Sample text </a> 
<?php 
} 
?>