在破坏YouTube将嵌入代码到变量中时遇到问题


having trouble breaking a youtube embed code up into variables

我正在尝试获取基本的 youtube 嵌入代码并将其分解为高度宽度和 url 的变量,但 im 使用的代码不断抛出错误。

<?php
$width = "10";
$height = "20";
$vid url = "http://www.youtube.com/embed/HjgSmoilwV4";
echo '<iframe width="'$width'" height="'$height'" src="'$vid'" frameborder="0"allowfullscreen></iframe>';
?>

使用此代码 IM 收到以下错误

解析错误:语法错误,第 4 行 D:''webdesign''webserver''root''dynapage''scripts''admin''add_video.php 中的意外T_STRING

我做错了什么?我在谷歌上搜索并找到了关于逃跑的东西,但不确定它希望我逃脱什么。

4 行$vid url ,那里不能有那个空格,这是一个语法错误。因此,请将其更改为:

$vid = "http://www.youtube.com/embed/HjgSmoilwV4";

最后一行应该是:

echo "<iframe width='".$width."' height='".$height."' src='".$vid."' frameborder='0' allowfullscreen></iframe>";

为了在字符串中使用变量,您需要在 PHP 中使用双引号。 所以以下内容:

echo '<iframe width="'$width'" height="'$height'" src="'$vid_url'" frameborder="0"allowfullscreen></iframe>';

应该是:

echo "<iframe width='$width' height='$height' src='$vid_url' frameborder='0' allowfullscreen></iframe>";

您收到语法错误,因为您使用了单引号,然后结束了它们,但后面仍有文本。您的示例代码也可以使用串联运算符编写 .

echo '<iframe width="' . $width . '" height="' . $height . '" src="' . $vid_url . '" frameborder="0"allowfullscreen></iframe>';

不能简单地将字符串与变量连接起来,方法是将它们放在源输入文件中。相反,请使用.来连接这些值:

$ php
<?php
echo 'one' 'two';
?>
PHP Parse error:  syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in - on line 2
$ php
<?php
echo 'one' . 'two';
?>
onetwo$ 

唯一缺少的连接 =]

<?php
    $width = "10";
    $height = "20";
    $vid url = "http://www.youtube.com/embed/HjgSmoilwV4";
    echo '<iframe width="'.$width.'" height="'.$height.'" src="'.$vid.'" frameborder="0" allowfullscreen></iframe>';
?>

有用的链接

  • 字符串运算符
<?php
$width = '10';
$height = '20';
$vid_url = 'http://www.youtube.com/embed/HjgSmoilwV4';
echo "<iframe width='"$width'" height='"$height'" src='"$vid_url'" frameborder='"0'" allowfullscreen></iframe>";
?>

在 PHP 中使用双引号 ("( 允许您按名称嵌入变量内容,因为脚本引擎会解析已知模式的双引号字符串。我用双引号替换了单引号,然后转义了所有双引号。

您的代码示例的主要问题是变量不能包含空格,因此我用下划线替换了空格。