Potato Gun
Potato Gun

Reputation: 163

Printing a string in a PHP script breaks the following HTML tags

So I am new to PHP development, and have been testing out a few scripts recently.

One script that I have attempted to create is one that retrieves the subscriber count of a given YouTube channel, and I have come up with the following script:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Test project.
        </title>
    </head>
    <body>
        <?php
            $json = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=Stackoverflow&key={API_KEY}');
            $subscribers = json_decode($json);

            var_export(current($subscribers->items)->statistics->subscriberCount);

            print '<p>' . $subscribers . "</p>\n";
        ?>
    </body>
</html>

However, this script seems to break the HTML document, because whenever the page is loaded any tags that come after the PHP script are removed.

Example (resulting HTML document after I use the script above):

<!DOCTYPE html>
<html>
    <head>
        <title>
            Test project.
        </title>
    </head>
    <body>
        '1'

As you can see, the document does not end with the appropriate </body> and </html> tags which are present in the original document.

I have attempted to validate the PHP document using various tools online, but have not managed to figure out the issue. Any help would be appreciated.

Upvotes: 0

Views: 87

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13645

$subscribers is an object, You can't print on object, unless you have created the class yourself and have added a __toString()-method.

This should work:

<?php
    $json = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=Stackoverflow&key={API_KEY}');
    $subscribers = json_decode($json);

    // Save the value in a variable first
    $count = current($subscribers->items)->statistics->subscriberCount;
    print '<p>' . $count . "</p>\n";

    // Or use it straight away
    print '<p>' . current($subscribers->items)->statistics->subscriberCount . "</p>\n";
?>

Upvotes: 1

Junho Cha
Junho Cha

Reputation: 163

I think under syntax is wrong. print '<p>' . $subscribers . "</p>\n";

How about make some temporal string variable to store $subscribers. ?

Upvotes: 1

Related Questions