Could use some help: json_decode not working


I ran into a problem today while pushing the local version of my portfolio site to my host and well, it doesn’t work. The most significant error has to do with a function I made which returns page content dynamically, utilizing the HTTP Header query, and fetching local files dynamically depending on logical checks.

I had to troubleshoot a bit to find where the problem seems to be localized, which is at a point I’m looping through the returned json results key via a foreach loop. The error states that I’m passing an invalid argument. Through further searching I was able to determine this was likely due to the json data returned is null. So though i’m getting an error in the loop, it’s actually with getting that JSON content, because all I was ever able to get were NULL values at that point of contact.

How It Works

Suposing url contains:$page=about, and with index calling Page function content():

The function will check if the page is a main page, if so it’ll match the value of page set in HTTP Header through switch statement for each page, if it matches a page it’ll use the make_page function. This function takes a path to the file which passes it along to a file getting function depending on the file type detected. The page loads php file just fine as the function fetching them uses an include, however for json files it seems to only return null values.

##The Code
The following code & information describe the situation

HTML: index.php (Page class assigned to $thePage)

    <!-- Content -->
    <!-- Nested under html>body>main -->
    <div class="page__content">
      <?php if ($thePage->isMain() || isset($_GET["post"])) : ?>
        <?php $thePage->content(); ?>
      <?php else: ?>
        <p>Sorry. . . Page failed to load.</p>
      <?php endif; ?>

PHP: Functions.php (Contains the Page Class which operates on index under all circumstances)

class Page {

    // Logicals: Manage situational checks
    // ----------------------------------------
    public $title = array (
        "sample"=> array("sample", "Sample"),
        "blog"=> array("blog", "Blog"),
        "work"=> array("work", "Portfolio"),
        "about"=> array("about", "About")

    function isMain() {
        // Page isMain if only page key detected; or neither is.
        if ( isset($_GET['page']) && !isset($_GET['post']) || !$_GET['page'] && !$_GET['post'] ) {
            return true;
        } else {
            return false;

    // Handlers: Manage data requests
    // ----------------------------------------
    function get_file($path) {
        include $path;

    function get_json($path) {
        // How to use file_get_contents with include path: file_get_contents('./path/to/file')
        $value = json_decode(file_get_contents($path, true), true);
        return $value;

     // Constructors: Manage data display
    // --------------------------------------------
    function make_body($jsonContent) {
        $value = $jsonContent;
        foreach ($value["content"] as $key) { //Echo Content Array
            echo $key;

    function make_page($pathParam="content/page/", $fileParam="page_welcome.html", $titleParam="title", $subParam="date") {
        // Is Json File?
        $isJson = strpos($fileParam, ".json") ? TRUE : FALSE ;
        // Grab Content
        $value = $isJson ? $this->get_json($pathParam.$fileParam) : $this->get_file($pathParam.$fileParam);
        // Header
        $header = $isJson ? $this->make_header($value[$titleParam], $value[$subParam]) : NULL;
        // Body
        $body = $isJson ? $this->make_body($value) : $value;

    // Operators: Deliver content to index & perform operations from page condition
    // -----------------------------------------------------------------------------
    function content() {
        // If Main
        if ($this->isMain()) {
            // Build Page
            // Check Page Type
            switch ($_GET['page']) {
                case $this->title["blog"][0] :
                    $isFilterOn = isset($_GET["filter"]) ? TRUE : FALSE;
                    if ($isFilterOn) {
                        switch ($_GET['filter']) {
                            case 'recent':
                                $this->make_page( 'content/posts/', 'static_PostItem_web.php');
                    } else {
                        echo '<section><h2>Error</h2><p>Filter is off...</p></section>';
                case $this->title["work"][0] :
                    $this->make_page('content/page/', 'page_work.json', null, null);
                case $this->title["about"][0] :
                    $this->make_page('content/page/', 'page_about.json', null, null);
                case 'sample':
                    $this->make_page('content/page/', 'page_sample.php', 'title', 'subTitle');
                case 'demo' :
                    $this->make_page('content/page/', 'page_welcome.html', null, null);
        // If Not
        else {
            // Build Post
            $this->make_page('content/posts/'.$_GET["filter"].'/', $_GET['post'].'.json', 'title', 'date');

If you follow the above links to the page (although they were used to suppose the situation) I have set up two sections, one showing an echo of file_get_contents, which returns the string from the file, and a var_dump of a json_decode being used on that file_get_contents result, with associate array option.

I’d really appreciate any input someone has. It must be a configuration issue?

Whats your Json look like your looks are returning a 404

I had to change the links to “com?page=about” then went to

Pasting into

gives me

Error: Parse error on line 7:
… ], “content”: [ "
< p > H
Expecting ‘STRING’, ‘NUMBER’, ‘NULL’, ‘TRUE’, ‘FALSE’, ‘{’, ‘[’, ‘]’, got ‘undefined’

I don’t know why the linter is adding whitespace that I don’t see in the source.

Maybe escaping the CSS “>” would help?

"<style>.profile > div { background-image: url(\"http://localhost/Emgo/content/gallery/Us.jpg\");</style>"

I was able to fix the json error being thrown by properly removing all of my line breaks in the middle of the string




or just

"<section> <p>"
1 Like

That was the problem, not escaping the CSS, but because I had lazily allow the strings to overflow multiple lines. I went through and close off each line with a [",].

Is there no way to allow a string to flow over multiple lines? Such as:

    String: [
        "This is one long string.
         That is easier to read on multiple lines.
         Is this not still counted as one index?",

AFAIK not in the JSON itself that would make it more “human friendly” to read.

But then, it is meant to be read by code, not humans.

According to what I see here

you could encode using

any-Unicode-character- except-"-or--or- control-character
\u four-hex-digits

but the string would still be on one line. eg.

"This is one long string.\n\tThat is easier to read on multiple lines.\n\tIs this not still counted as one index?"
1 Like

Right, that would affect the output. I had formatted my JSON files properly at one point, yet they are much easier to maintain with the format they are in; and I figured since my local development parses them fine (still curious as to why that is) that it was allowed.

Thanks for going to the JSON file, I was certain the problem had to do with php or my function somehow. I’ll fix the rest of my JSON files now. You saved me a couple more hours of troubelshooting! Much Appreciated! :wink:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.