1

我试图通过在 HTML 链接中使用 PHP 函数来调用网站根目录。

我在下面创建了函数 bloginfo() ,正确的链接输出是http://www.example.com/subdirectory/file.php

调用函数的两种方法相似,但方法 1 不起作用方法 2 起作用

请有人解释为什么方法1不起作用并提出解决方案。谢谢。

<?php
function bloginfo($show) {
switch ($show) {
    case 'template_url':
        echo "www.example.co.uk";
        break;
}
}

// Method 1 - does not work
echo "<a href=\"http://<?php bloginfo('template_url'); ?>/subdirectory/file.php\">test link 1</a>";

?>
<html>
<body>

<!-- Method 2 - works! -->
<a href="http://<?php bloginfo('template_url'); ?>/subdirectory/file.php">test link 2</a>

</body>
</html>  

更新

echo "<a href=\"http://".bloginfo('template_url')."/subdirectory/file.php\">

谢谢大家的帮助。不幸的是,由于某种原因,我无法获得通用答案(代码行上方),但会打印“www.example.com”但不会作为链接,并且链接方向只是变成了“/subdirectory/file.php” .

为了解决这个问题,我放弃了合并一个函数并决定简单地使用下面的 PHP 定义方法,该方法适用于两种方法。

<?php

//this line of code can be put into an external PHP file and called using the PHP Include method.
define("URL", "www.example.com", true);

// Method 1 - works!
echo "<a href=\"http://".URL."/subdirectory/file.php\">test link 1</a>";

?>
<html>
<body>

<!-- Method 2 - works! -->
<a href="http://<?php echo URL; ?>/subdirectory/file.php">test link 2</a>


</body>
</html>  
4

4 回答 4

6

双引号字符串使您在第一种方法中的 php 块只是一个普通的旧文本字符串。尝试这个:

  echo "<a href=\"http://".bloginfo('template_url')."/subdirectory/file.php\">test link 1</a>";
于 2012-10-31T23:13:14.603 回答
1

你已经嵌套了一些 php 标签

echo "<a href=\"http://" .bloginfo('template_url') . "/subdirectory/file.php\">test link 1</a>";
于 2012-10-31T23:14:03.317 回答
0

或这个:

echo "<a href=\"http://{bloginfo('template_url')}/subdirectory/file.php\">test link 1</a>";
于 2012-10-31T23:20:15.820 回答
0

这是因为您在标签内使用并且没有告诉它回显。下面的代码可以工作 - 我已经注释掉了你的旧行并添加了一个可以工作的新行

<?php
function bloginfo($show) {
  switch ($show) {
    case 'template_url':
    echo "www.example.co.uk";
    break;
  }
}

// Method 1 - does not work
//echo "<a href=\"http://<?php bloginfo('template_url'); ?>/subdirectory/file.php\">test link 1</a>";

echo "<a href=\"http://".bloginfo('template_url')."/subdirectory/file.php\">test link 1</a>"; <--- changed the above line to this... now both this and the lower line work


?>
<html>
<body>

<!-- Method 2 - works! -->
<a href="http://<?php bloginfo('template_url'); ?>/subdirectory/file.php">test link 2</a>

</body>
</html>  
于 2012-10-31T23:42:24.247 回答