我正在尝试使用PHP和HTML将图像制作成链接。主要思想是从Twitter上获取用户的图像和屏幕名称,然后通过构建URL并在其末尾添加其屏幕名称,使图像成为指向其个人资料的可点击链接。但是我收到一条错误消息:
解析错误:语法错误,意外的T_CONSTANT_ENCAPSED_STRING,期望为','或';'在第71行的C:\ wamp \ www \ fyp \ tweeter3.php中。
这是第71行(它是foreach循环的一部分):
<?php echo "<a href = ".$url"><img src = ".$userImage." class = ".$class."></a>"; ?>
我无法确切指出其中存在语法错误。这些是我的变量:
$userScreenName = $user -> screen_name;
$userImage = $user -> profile_image_url;
$class = "myImgClass";
$url = "https://twitter.com/".$userScreenName;
您能发现错误吗?
您在$ url和HTML引号后缺少一个点以生成有效代码:
<?php echo "<a href = '".$url."'><img src = '".$userImage."' class = '".$class."'></a>"; ?>
没有报价,您会得到:
<a href = the url><img src = user image class = the class></a>
带引号:
<a href = 'the url'><img src = 'user image' class = 'the class'></a>
.
之后缺少$url
:
<?php echo "<a href = ".$url"><img...
$ url之后,您需要使用句点。
尝试以下方法:
<?php
echo "<a href = \"".$url."\"><img src = \"".$userImage."\" class = \"".$class."\"></a>";
?>
我认为,最简单,最易读的方法是:
<?php echo "<a href = '$url'><img src = '$userImage' class = '$class'></a>"; ?>
只有一个长文本,不使用任何串联。它减少了由于缺少双引号或点引起的错误的可能性。所有PHP变量都将自动替换为其值。
您也可以使用printf使所有变量都位于字符串之外:
<?php printf('<a href = "%s"><img src = "%s" class = "%s"></a>', $url, $userImage, $class); ?>
将html字符串与php变量连接不是一个好习惯。这导致可能的注入向量(XSS)。为避免可能的XSS(DOM或STORED),请将变量过滤为字符串。特别是如果该值来自用户输入。例如。
<?php echo "<a href = '".filter_var($url, FILTER_SANITIZE_STRING)."'