I am attempting to iterate through a foreach loop, but I am encountering an error stating that the argument is invalid. What could be

I attempted using the if(is_array()) function, but instead of getting an error message, the h1 heading just kept appearing. I checked my code on phpcodechecker and it showed no issues, but when I run it on my browser, I keep encountering an "invalid argument for the foreach()" error. I even tried changing $json to $jsondata, but that didn't solve the problem either. Can someone help me understand why this foreach loop is returning an invalid argument?

<?php
        $jsondata = file_get_contents("movies.json");
        $json = json_decode($jsondata, true);
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                h1 {text-align: center;}
                h4 {margin:0; padding:5px; background:#f4f4f4;}
                li{list-style:none; padding-left:5px;}
                #container {width: 600px;}
            </style>

            <title>PHP Loops: My Movies</title>

        </head>

        <body>
            <div id="container">
                <h1>My Favorite Movies</h1>
                <ul>
    <?php

    foreach($json['movies.json'] as $key => $value) {
            echo '<h4>'.$value['title'].'</h4>';
            echo '<li>Year: '.$value['year'].'</li>';
            echo '<li>Genre: '.$value['genre'].'</li>';
            echo '<li>Director: '.$value['director'].'</li>';
        }



    ?>
                </ul>
            </div>


        </body>

    </html>

Answer №1

Additional information from the comments:

The issue lies with the incorrect data in the .json file, causing decoding errors.

A correct sample of the data can be found here: http://example.com/sample-json. Make sure to navigate through $json['movies'].

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP's include/require method with a dynamic path

Looking for assistance with my issue! Ajax is returning the correct information and displaying it in an 'alert(html)' on 'success'. The PHP code echoes $idName and $path correctly on the carrier page where the code resides. There are no ...

Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try. So far, here's what I've done: Inserted code into themes functions.php function test_my_script() { wp_register_script( 'custom-s ...

The json_decode function results in a null value

I save encrypted collections in a database, but when I attempt to decipher them, they come back as null. [{"id":13,"qty":"1"}] The arrays are encrypted using PHP, so I am unsure of what the issue could be. Appreciate any help. ...

Prestashop Webservice Feature: Managing Multiple Cart Rows

I've been dealing with PrestaShop 1.6 and have successfully set up the webservice (API) with Prestashop, but I've encountered a minor issue with the cart adding process. Essentially, when I try to create my cart, each additional item I add (cart ...

Contact Company by Sending Email According to Selected Product Dropdown Choice

If a customer selects a specific business option from the dropdown menu on the product page, I want to send the standard WooCommerce Order Confirmation Email to both the site admin and that selected business. Backpack $50 Choose an Option Business First ...

Show all entries belonging to a specific ID on individual rows for each ID using PHP

I have a table generated from inner joins that displays different articles associated with outfit IDs. id_outfit | name | article ---------------------------------------- 56 | one | shoe.png 56 | one | dress.png 56 | one ...

Refreshing of JSON data does not occur

I'm currently working on developing an Android app that involves JSON Parsing. I have a php script hosted on my server that fetches data from a MySQL database and encodes it to JSON. The app communicates with the server to retrieve this data and popul ...

Nest an array inside another array using a foreach loop

I've successfully created a code that generates two arrays using foreach loop and existing data. Now, I am looking to merge these two arrays into one. Below is the code for the first array : $sql = "SELECT photoprofile,username from photo WHERE usern ...

Looking to update a component in Vue 3 and Laravel 9 without the need to reload the entire webpage

Looking for a solution to refresh the header component upon clicking the logout button, in order to display the login and register options without refreshing the entire page. Any effective suggestions on how to achieve this are greatly appreciated. The l ...

How to utilize PHP to create a multiple select form for filtering results in a MySQL

I have been attempting to create a query using the results from a search form. In my form, I have a field called "state". My goal is to allow users to select multiple states and receive a list of results that include all the selected states. Currently, I o ...

Determine in PHP if a decimal number is greater than 0.3

Trying to find out if a number has a decimal using the following code snippet. Example: $val = 3.3; if (is_numeric( $val ) && floor( $val ) != $val) { return true; } Is there a way to determine if the decimal value of the number is equal to o ...

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

Joomla update query malfunctioning - seeking resolution

Currently, I am in the process of developing a Joomla extension and I am attempting to update entries within my Joomla extensions database table using the code snippet below in my model: $this->_db->setQuery( $this->_db->getQu ...

Using an Ajax request, form data is captured and then sent via POST to a PHP script in order to be added

I'm feeling a bit out of my depth with this, but here's the situation. I inherited a form that has one input field for email and a submit button. The code was not written by me, so I'm struggling to understand it. I've tried researching ...

What is the process of running PHP in a .ctp file within the CakePHP framework?

I have recently started working with CakePHP and I have a question about how PHP code is executed in a file with the .ctp extension. Can you explain how PHP is processed within a .ctp file in CakePHP? Additionally, I'm also curious about executing PHP ...

Successful query execution is achieved in phpMyAdmin but fails when attempted in PHP

Is there a reason why a query in PHP may not return the same data as it does in phpMyAdmin SQL? $query = "UPDATE `boards` SET `contestPlaces`=0, `contestPlacesFilled`=0"; $result = mysql_query($query) or die("ERROR:QUERY_FAILED timeset 8" . mysql_error( ...

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

The value of ajax data at index 0 is not defined

When using AJAX to retrieve the number of rows from a SQL query in PHP, the JSON return shown in the Firefox Network tab is [{"number":2}], with the number 2 being without quotes. However, when trying to access the value (2) using data[0]["number"] or dat ...

Utilizing the chain method in the PDO class

This is a "wrapper" class that utilizes PDO (although it is quite extensive, the important segment is highlighted here) class DB { protected $pdo; protected $dsn; protected $username; protected $password; protec ...

Is it possible to prevent PHP users from accessing files through a URL?

Is there a method to prevent users from directly accessing a specific file in a designated directory via URL, while still allowing a PHP script to manage and retrieve the file? In simpler terms, I aim to hinder individuals from inputting: . Perhaps redire ...