将动态变量嵌入到一个html url字符串中,并获取它的html代码


get dynamic variable embed into a string of html url and get the html code of it

有人能帮我获取页面的代码吗?我使用的代码是:

<?php
$v='bla bla';
$j=2;
$x='';
$h=str_replace($x,$v,"http://www.youtube.com/watch?v=$x&list=blabla&index=$j++&feature=plpp_video");
$html = file_get_contents($h);
echo $html;
?>

wamp抛出了一个类似的错误

Warning: file_get_contents(http://www.youtube.com/watch?v=&list=blabla&index=2&feature=plpp_video)
[function.file-get-contents]: failed to open stream:
HTTP request failed! HTTP/1.0 404 Not Found in C:'wamp'www'php trails'trails'new 8.php on line 6

如果x没有被声明为null,它会说:

Notice: Undefined variable: x in C:'wamp'www'php trails'trails'new 8.php on line 5

http://www.youtube.com/watch?v=&list=blabla&索引=2&feature=plpp_video不是有效的url

我想你想要那种

$v='bla_bla';
$j=2;
$h = "http://www.youtube.com/watch?v=".$v."&list=blabla&index=".($j++)."&feature=plpp_video";
$html = file_get_contents($h);
echo $html;

edit:从字符串中排除$v以突出显示更改

当您只连接一些字符串时,不需要替换字符串。您可以将变量作为{var}直接写入字符串。确保你的vars是url编码的。

<?php
$v='bla bla';
$j=2;
$x='';
$h="http://www.youtube.com/watch?v={$x}&list=blabla&index={$j}++&feature=plpp_video");
$html = file_get_contents($h);
echo $html;
?>

您误解了str_replace()和字符串在PHP中的一般工作方式。

试试这个:

<?php
  $v = 'bla bla';
  $j = 2;
  $urlTemplate = 'http://www.youtube.com/watch?v=%x%&list=blabla&index=%j%&feature=plpp_video';
  $h = str_replace(array('%x%','%j%'), array($v,$j++), $urlTemplate);
  echo file_get_contents($h);

将变量放入字符串中时,将在解析字符串时(即赋值时)对其求值。您所做的操作将不起作用,因为字符串的计算结果将为http://www.youtube.com/watch?v=&list=blabla&index=2++&feature=plpp_video

字符串中的变量不会创建对变量的引用,它们只是使用当前值。

上面的代码使用占位符%x%%j%,并将它们替换为要使用的实际值。

我发现不需要操纵url中的值,每个视频都有一个唯一的id,所以不需要麻烦增加/更改索引值或播放列表值