search

Home  >  Q&A  >  body text

Extract and access JSON data using PHP

<p><br /></p><blockquote> <p>This is a general reference question and answer that covers many of the never-ending "How do I access data in JSON?" questions. It deals here with the broad basics of decoding JSON in PHP and accessing the results. </p> </blockquote> <p>I have JSON: </p> <pre class="brush:php;toolbar:false;">{ "type": "donut", "name": "Cake", "toppings": [ { "id": "5002", "type": "Glazed" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5004", "type": "Maple" } ] }</pre> <p>How to decode it and access the resulting data in PHP? </p>
P粉448346289P粉448346289443 days ago436

reply all(1)I'll reply

  • P粉681400307

    P粉6814003072023-08-29 09:39:34

    <?php
    $jsonData = '{
        "type": "donut",
        "name": "Cake",
        "toppings": [
            { "id": "5002", "type": "Glazed" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5004", "type": "Maple" }
        ]
    }';
    
    // Decode the JSON
    $data = json_decode($jsonData, true);
    
    // Access the data
    $type = $data['type'];
    $name = $data['name'];
    $toppings = $data['toppings'];
    
    // Access individual topping details
    $firstTopping = $toppings[0];
    $firstToppingId = $firstTopping['id'];
    $firstToppingType = $firstTopping['type'];
    
    // Print the data
    echo "Type: $type\n";
    echo "Name: $name\n";
    echo "First Topping ID: $firstToppingId\n";
    echo "First Topping Type: $firstToppingType\n";
    ?>

    In this example, json_decode() is used to decode JSON data into a PHP associative array. You can then access the individual elements of the array just like any PHP array.

    reply
    0
  • Cancelreply