krishna
krishna

Reputation: 960

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

Can someone help me to get the code of the page? The code I used was:

<?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 is throwing an error like

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

if x is not declared to null, it says:

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

Upvotes: 1

Views: 775

Answers (4)

krishna
krishna

Reputation: 960

i found that there is no need of manipulating values in the url, each video carries an unique id so no need to bother about incrementing/altering index value or playlist value

Upvotes: 0

Dirk Leuther
Dirk Leuther

Reputation: 103

There is no need to replace strings when you just join some strings. You can write the variables as {var} direct into your string. make sure your vars are url encoded.

<?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;
?>

Upvotes: 2

rauschen
rauschen

Reputation: 3996

http://www.youtube.com/watch? v=& list=blabla&index=2&feature=plpp_video is no valid url

I think you want something like that

$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: excluded $v from the string to highlight the change

Upvotes: 2

DaveRandom
DaveRandom

Reputation: 88697

You are misunderstanding how str_replace() and strings in general work in PHP.

try this:

<?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);

When you place a variable in a string, it is evaluated at the time the string is parsed - at the time of the assignment. What you have done will not work because the string would evaluate to http://www.youtube.com/watch?v=&list=blabla&index=2++&feature=plpp_video.

The variables in the string do not create a reference to the variable, they simply use the current value.

The code above uses the placeholders %x% and %j% and replaces them with the actual values that you want to use.

Upvotes: 0

Related Questions