2013-07-15 44 views
0

這是我與工作代碼:PHP變量插入到鏈接href和名稱

<?php 
    $rss = new DOMDocument(); 
    $rss->load('http://hugeriver.wordpress.com/feed/'); 
    $feed = array(); 
    foreach ($rss->getElementsByTagName('item') as $node) { 
     $item = array ( 
      'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 
      'desc' => $node->getElementsByTagName('encoded')->item(0)->nodeValue, 
      'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 
      'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue, 
      ); 
     array_push($feed, $item); 
    } 
    $limit = count($feed); 
    for($x=0;$x<$limit;$x++) { 
     $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']); 
     $link = $feed[$x]['link']; 
     $description = $feed[$x]['desc']; 
     $date = date('l F d, Y', strtotime($feed[$x]['date'])); 
     echo '<h2><a name="test">'.$title.'</a><span class="line"></span></h2>'; 
     echo '<small><em>Posted on '.$date.'</em></small></p>'; 
     echo '<p>'.$description.'</p>'; 
    } 
?> 

我這一行專門卡住。我試圖讓它成爲標題既是ancor的名稱又是鏈接(所以點擊它就會滾動到頂部)。這是我嘗試過的不起作用。任何人都可以告訴我我的語法有什麼問題嗎?

echo '<h2><a name="'.$title'" href="#'.$title'">'.$title.'</a><span class="line"></span></h2>'; 
+0

您的2代碼塊上的缺失點是否爲錯字?我會認爲這是因爲你的主代碼塊有'''。$。''和''''。'$''''' – Prix

回答

-1
echo '<h2><a name="'.$title.'" href="#'.$title.'">'.$title.'</a><span class="line"></span></h2>'; 

您在$標題後無點

此外,您鏈接鏈接到自理。你需要定義一個獨立的錨點然後鏈接到它。

+0

''echo'與'.'意味着無意義的連接。 'echo'接受','。所以不要'迴應'爲什麼''串聯'''這個';'但是''echo','does','it','for' – CodeAngry

3

您目前正在創建一個以自己爲目標的鏈接。

如果你想鏈接到點擊時文件的頂部,只需鏈接到'#'

<a href="#" name="<?php echo $title ?>"><?php echo $title ?></a> 

此外,name is deprecated on <a/> elements in HTML 5。使用id代替:

<a href="#" id="<?php echo $title ?>"><?php echo $title ?></a> 
+0

我想要點擊鏈接時轉到標題。所以,而不是ahref =#我想ahref = $標題請 –

+0

你想鏈接去自己? '' –

0

有兩個缺失點。

試試這個:

echo '<h2><a name="'.$title.'" href="#'.$title.'">'.$title.'</a><span class="line"></span></h2>'; 
0

試試這個語法

echo "<h2><a name=\"$title\" href=\"#$title\">$title</a><span class=\"line\"></span></h2>"; 

echo "<h2><a name='$title' href='#$title'>$title</a><span class='line'></span></h2>"; 

這是更清潔,並有遺漏點或關閉/打開引號的概率較小。

1
<a href="#" ID="<?php echo htmlentities($title, ENT_QUOTES); ?>"> 
    <?php echo htmlentities($title, ENT_NOQUOTES); ?></a> 

爲什麼每個人都忘記htmlentities(),尤其是對屬性?

爲什麼用$title作爲#target?當$title是一個空格和標點不適合的變量#target練習...爲什麼不使用md5($title)因爲您動態生成頁面?像:

<a href="#" ID="<?php echo htmlentities(md5($title), ENT_QUOTES); ?>"> 
    <?php echo htmlentities($title, ENT_NOQUOTES); ?></a> 

後來就鏈接到它是這樣的:

<a href="#<?php echo htmlentities(md5($title), ENT_QUOTES); ?>"> 
    Go to <?php echo htmlentities($title, ENT_NOQUOTES); ?>!</a> 
1

安德烈答案應該解決您的問題,如果你想要做的就是簡單地去到頁面頂部什麼。但是如果你想要去擁有ID爲$標題的值,那麼你可以試試這個特定的部分...

<a href="#<?php echo $title ?>" name="<?php echo $title ?>"><?php echo $title ?></a> 

這樣,當鏈接被點擊就會跳轉到確切元素與編號等於標題(可能或不可位於頂部)。我相信這是你想達到的。