如何通过 PHP 中的回显让变量在 HTML 中输出

How to get variables to output in HTML via an echo in PHP

<?php
$request_uri = $_SERVER['REQUEST_URI'] ;

$path=explode("?",$request_uri);

$pname=basename($path[0]);

if ($pname == "blood-facts-for-kids.html") { $p1 = 'Human Body Facts'; $p1u = 'https://www.factsjustforkids.com/human-body-facts.html'; $p2 = 'Blood Facts'; $p2u = 'https://www.factsjustforkids.com/human-body-facts/blood-facts-for-kids.html'; }

echo '<script type="application/ld+json">{"@context":"https://schema.org/","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"{$p1}","item":"{$p1u}"},{"@type":"ListItem","position":2,"name":"{$p2}","item":"{$p2u}"}]}</script>';

?>

我在让变量出现在我的 echo 中时遇到问题。一切正常,如果网页名称正确并且我使用

自行回显变量,则会设置变量
echo "{$p1}, {$p1u}, {$p2}, {$p2u},";

显示了正确的数据。我显然在回显代码中做错了什么。

仅供参考,这是一种动态注入结构化数据的粗略方法。

您可以使用
echo $variable_name //显示变量

如果您想在 HTML 标签中显示它,那么

<p>Your age is <?php echo $age ?>.</p> 

我提供 link 以获得更详细的信息 https://www.dummies.com/programming/php/how-to-display-php-variable-values/

要么使用带双引号的 echo "":

echo "<script type=\"application/ld+json\">{\"@context\":\"https://schema.org/\",\"@type\":\"BreadcrumbList\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"{$p1}\",\"item\":\"{$p1u}\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"{$p2}\",\"item\":\"{$p2u}\"}]}</script>";

或使用串联:

echo '<script type="application/ld+json">{"@context":"https://schema.org/","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"' . $p1 . '","item":"' . $p1u . '"},{"@type":"ListItem","position":2,"name":"' . $p2 . '","item":"' . $p2u . '"}]}</script>';
  • 请注意,对于 double-quotes,您需要转义字符串中的任何其他双引号。