KJThaDon
KJThaDon

Reputation: 416

variable inside function not recognized

I am trying to pass a variable inside my function to parse when echoed in the url, however i am getting errors saying it is not defined. the variable $plex_token.

function getPlexXML($url)
{
libxml_use_internal_errors(true);
$plex_token = 'xxxxxxxxxx';
$xml = simplexml_load_file($url);
$count = number_format((float)$xml['totalSize']);

if (false === $xml) {
    echo '<div class="counter_offline">N/A</div>';
} else {
    echo '<div class="counter_live">'.$count.'</div>';
}
}

echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');

Upvotes: 1

Views: 31

Answers (1)

DanielRead
DanielRead

Reputation: 2794

It's because you're referencing $plex_token outside of the context that it was defined in.

You defined it inside of the function "getPlexXML" but then you're using it outside of that function as a parameter being passed into getPlexXML.

You can do one of the following:

A) Define it outside of the function since you're not using it in the function:

$plex_token = 'xxxxxxxxx';

function getPlexXML($url){
      // You cannot use $plex_token in here
      ...
}

echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');

OR B) Make it a global variable then you can use it inside or outside the function:

$plex_token = 'xxxxxxxxx';

function getPlexXML($url){
     global $plex_goken;
     // You can use $plex_token in here
     ...
}
echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');

Upvotes: 1

Related Questions