Utilize a stored string as the destination for the content of an object

We are currently working on processing a large amount of json data and trying to specify which parts of it to use using string variables.

My goal is to convert a string into an object path to access the content of an item.

The following code works correctly:

<?php 
$pmdd_ds_json_obj = json_decode($pmdd_ds_json_data);
echo $pmdd_ds_json_obj[0]->title->rendered; // displays "Wisconsin Investment Board"
?>

However, I am unable to achieve the same outcome with the code below:

$num = 0;
$root =  "pmdd_ds_json_obj[$num]->";
$content = "title->rendered"
$obj_content = ${$root.$content};

// I have also tried different approaches.
echo $root.$content;
echo ${$root.$content};
echo ${"$root.$content"};

Is what I'm attempting even possible? I have attempted numerous variations and would appreciate a fresh perspective!

json data

[{
    "date": "2019-07-04T10:21:15",
    "title": {
        "rendered": "Wisconsin Investment Board"
    },
    "_links": {
        "self": [{
            "href": "https:\/\/refi.global\/europe\/wp-json\/wp\/v2\/posts\/309891"
        }]
    }
}]

Answer â„–1

Using dynamic variables will not work with array keys or arrow operators as you've attempted. While you could achieve this using eval(), it is not recommended.

Instead, consider using the json_decode function with a flag set to return an associative array instead of stdClass objects. More information can be found at this link.

$foo = json_decode($json, true);

To access the desired value, you can create a function that resolves array values by dot notation and store it in a variable. Refer to this answer for more details: here.

<?php

$json = '[{
    "date": "2019-07-04T10:21:15",
    "title": {
        "rendered": "Wisconsin Investment Board"
    }
}]';

// decode as an associative array
$pmdd_ds_json_obj = json_decode($json, true);

/**
 * @link https://stackoverflow.com/a/14706302/2286736
 */
function resolve(array $a, $path, $default = null) {
    $current = $a;
    $p = strtok($path, '.');

    while ($p !== false) {
        if (!isset($current[$p])) {
            return $default;
        }
        $current = $current[$p];
        $p = strtok('.');
    }

    return $current;
}

// key variable
$key = '0.title.rendered';

// value can be resolved by the dot notation path
$value = resolve($pmdd_ds_json_obj, $key);
var_dump($value); // Wisconsin Investment Board

Further modifications to the resolve() function allow it to accept objects as inputs:

$json = '[{
    "date": "2019-07-04T10:21:15",
    "title": {
        "rendered": "Wisconsin Investment Board"
    },
    "_links": {
        "self": [{
            "href": "https:\/\/refi.global\/europe\/wp-json\/wp\/v2\/posts\/309891"
        }]
    }
}]';

// decode without specifying return type (using stdClass)
$pmdd_ds_json_obj = json_decode($json);

function resolve($a, $path, $default = null) {
    $current = $a;
    $p = strtok($path, '.');

    while ($p !== false) {
        if (
            (is_array($current) && !isset($current[$p]))
            || (is_object($current) && !isset($current->$p))
        ) {
            return $default;
        }
        $current = is_array($current) ? $current[$p] : $current->$p;
        $p = strtok('.');
    }

    return $current;
}

// key variable
$key = '0._links.self.0.href';

// value can be resolved by the dot notation path
$value = resolve($pmdd_ds_json_obj, $key);

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

Access JSON information from a URL by utilizing Java

I have read some answers like Simplest way to read JSON from a URL in Java but it did not work. Okay, here is my code: package day1; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import org.json.simple.JSONArray; imp ...

What is the process for retrieving external JSON using PHP with a content-type of text/plain?

I am attempting to retrieve an external JSON response using my PHP backend. However, I am encountering an issue where the external endpoint is returned with the Content-Type: text/plain;charset=utf-8, resulting in unreadable content. string 'ï¿½ï¿½ï¿ ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

html line breaks $.parseJSON

Within my website, I am currently utilizing a TinyMCE window. The method involves PHP fetching an entry from the database, decoding it as JSON, and then having in-page JavaScript parse it. However, issues arise when there are elements like style='colo ...

Converting Data from MySQL and PHP to Excel

Is there a way to export human resource applications stored in my MySQL table as an Excel file? function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){ global $connect; header('Content-Enc ...

The filesize() function consistently returns 0 bytes, despite the fact that the actual file size is not 0 bytes

I have written some code below and I am currently testing it, so there are no database queries in the code yet. In the code below, where it checks if(filesize($filename) != 0), it always goes to the else block even though the file is not empty and has 16 ...

What are the alternatives to using Node.js for implementing real-time chat functionality in core PHP using socket.io?

I am in the process of integrating socket.io into my core PHP custom framework. I prefer not to use node.js because it may cause conflicts with my existing AJAX code. 1) Is there a way to use socket.io without relying on node.js? 2) If node.js is necessar ...

js issue with passing form data to use with PHP mail function

As a novice, I am diving into the world of HTML webpage creation. Utilizing a free online template, my current project involves developing a Contact Page that triggers a php script to send an email with the captured fields. While I've successfully man ...

Get JSON or partial HTML responses from ASP.NET MVC controller actions

Is there a recommended method for creating controller actions that can return either JSON or partial HTML based on a specified parameter? I'm looking for the optimal way to asynchronously retrieve the results in an MVC page. ...

I successfully set up ApacheOpenmeetings on a dedicated server. Now, I am wondering how to connect to its REST APIs from a different application

Encountering the following error when making a request from localhost:- XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed acces ...

Receiving response in JSON format from a web service

I have been attempting to retrieve a JSON response from a web service, but the response I am receiving contains XML. It looks like this: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">[["123","testing123"]]</stri ...

unable to show image retrieved from JSON data

Looking to showcase the data from my JSON objects, which are displayed in 2 images below https://i.stack.imgur.com/yhqFy.png https://i.stack.imgur.com/DUgFO.png In the data, I have properties like c_name, max_slots, and an array slots. Within the array, ...

"Moisten" a JavaScript object instance using a JSON array, similar to the way PHP does

When populating PHP objects with data, I typically use the following method: public function hydrate(array $data){ foreach($data as $key=>$value){ $method = 'set'.ucfirst($key); if(METHOD_EXISTS($this,$method)){ ...

Issue with Laravel's with() method and search functionality using LIKE is not functioning as expected

My current setup involves 2 tables. One table is for storing debt information (id, amount, category_id), while the other table is used for debt categories (id, name). I am attempting to retrieve data based on each month from the debt table. However, I have ...

Handling Responses in Node.js using Express

I am completely new to using express (or any JS backend) so please forgive me if this question has already been answered or if it seems silly. I have successfully set up an endpoint. app.get('/hello-world'), async (req, res) => { try { ...

The PHP script unexpectedly terminates when attempting to download a file using Net_SFTP

While running a script that downloads 2 files from 2 different servers, I've encountered some issues. Sometimes the page stops loading or displays a 500 Internal Server Error. The timing of these errors is inconsistent and perplexing because there are ...

Deleting a database row when the cancel button is pressed

I have a scenario where I need to remove a database row containing a file name when the user clicks on the cancel button. However, despite my efforts, the database row is not being deleted. Can anyone help me identify what I might be doing wrong? Here is ...

What is the appropriate SQL query to search for perfect matches?

I want to find out the SQL command that will search for exact matches instead of using the "like" operator. The code below currently searches for similar results based on the query variable. $query = "SELECT languages.language FROM languages WHERE langu ...

JSON response and service status in a WCF REST service

A WCF REST service is returning a JSON response as follows: { "categories": [{ "category_id": "10", "name": "Grocery", "freeQnty":"0", "prdcost":"100" }, { "category_id": "20", "name": "Beverages", ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...