Obtaining JSON data in a separate JavaScript file using PHP

I have an HTML file with the following content:

// target.html
<html xmlns="http://www.w3.org/1999/xhtml">
...
<script src="../../Common/js/jquery-ui-1.10.3.js"></script>
<script src="../../Common/js/select.js" type="text/javascript"></script>
<script type="text/javascript">
    var JsonData = [{"one":[{"ID":4179,"Name":"Jack"},{"ID":4180,"Name":"Jill"}]}];
...

This file includes a JSON object named 'JsonData'. I am trying to access and display this JSON data using PHP. Here is my current approach:

// test.php
include ("./target.html");
readfile ("./target.html");

$html = file_get_html("/Users/Desktop/target.html");
// create a new DOM object
$dom = new domDocument('1.0', 'utf-8');
// load the HTML into the DOM object ***/
$dom->loadHTML($html);

$target= $dom->getElementsByTagName("script"); // you can use your desired tag here    
print_r($target);

However, I am unable to retrieve the JSON data using this method. Could someone please assist me with this issue?

Answer №1

file_get_html is not available in the version of PHP I am using, so I decided to utilize file_get_contents instead, which comes built-in with PHP. Additionally, I made a modification to your code by replacing print_r with the necessary code to resolve the issue you are facing. In your HTML file, there are a total of 3 script tags, and I accessed them using an index value of 2, noting that indexes start at 0.

// test.php
include ("./target.html");
readfile ("./target.html");

$html = file_get_contents("/Users/Desktop/target.html"); //replaced file_get_html
// creating a new dom object
$dom = new domDocument('1.0', 'utf-8');
// loading the html content into the object ***/
$dom->loadHTML($html);

$target= $dom->getElementsByTagName("script"); // here u use your desired tag    

echo $target->item(2)->nodeValue; //replaced print_r

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

An error message is displayed when attempting to retrieve a json response

After implementing my flask app, I noticed that the following code snippet is being returned: return json.dumps({'status': 'OK','url': 'www.blahg.com'}) Upon inspecting my javascript code, I found it to be structur ...

Browse through different states by clicking on the <a> </a> tag

Is there a way to switch between states defined by $stateProvider when clicking on the <a> </a> tag? Below are the states I have set up: $stateProvider //region page States .state('page1', { url: "/pg1", ...

What are some effective methods for maintaining the integrity of HTML content?

Attempting to safeguard HTML content generated in a specific location by powerMTA. Here is the code snippet of the HTML content. Content-1. <html>=0A<body>=0A<table style=3D"max-width:576px;font-family:Arial, Helvet= ica, sans-serif;&q ...

Exploring the Document Object Model to locate the adjacent sibling of a parent element

If I need to implement an event that hides the section .dependent-box whenever the element with class .radio-click-hide is clicked, what would be the best approach for traversing the elements to achieve this functionality? I have attempted the following co ...

Utilizing Node.js to create a REST API that allows for seamless communication with a MongoDB database through

Currently, I am developing a web application utilizing the MERN framework (MongoDB, Express, Node.js for back-end, React for front-end). One specific part of my web application requires frequent access to a collection in the MongoDB database (every 50 ms) ...

What could have caused the lack of output from the render function?

I've been working on generating my navigation drawer from JSON data and have everything functioning using components. Now, I'm in the process of refactoring to functions for better performance and to enhance my knowledge of React and JavaScript. ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...

Arrange a set of items using AngularJS according to specific criteria

Hello, I'm new to Angular I've created an angular app and you can view it in this plunkr. Can someone guide me on how to sort the list displayed here using angular? I want the course with the flag to always stay on top, while sorting the rest o ...

linking to a page that shows the user's chosen option from a dropdown menu

One of the challenges I encountered was creating a feature that allows users to share a specific selection from multiple dropdown lists on a page. Essentially, my goal was to enable users to send a link that would direct others to the same page with the ex ...

Postponed attaching event listeners to a Vue 3 instance within an iframe

Due to a specific requirement, I find myself in need of running a Vue instance inside an iframe. After some research and adjustments based on this thread from the Vue forum, I was able to achieve this goal while adapting the code for Vue 3 and removing unn ...

Using Gson to deserialize a Map<String, List<?>>

When working on my server, I first serialize data using the following code: Gson gson = new Gson(); Map<String, List<?>> resultMap = BackendUpdateManager.getInstance() .getUpdates(timeHolder, shopIdInt, buyerIdInt); gson.toJson(resultMap); ...

Material-UI Date Selectors: Show the Date in (Month, Day, Year) Format -> (April 17, 2019)

If you're using the Material-Ui Pickers library, check out this link for more information: It appears that you can display the date as a (Month Day) string or as a (MM/DD/YYYY) format. However, I'm wondering if there is an option to display the ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

Is there a way to transmit a float array from Scala using JeroMQ to C via ZMQ without the need for serialization or deserialization?

I am currently facing an issue where the JSON library I am using to serialize and deserialize data (JeroMQ for sender and C, ZMQ for receiver) is consuming excessive memory during parsing. This leads to the OS killing the process. To address this, I want t ...

"Sending an array in a POST request using Javascript and processing it on the server

I am trying to use ajax to send an array. Let's say the array looks like this: var anotherOne = 'anotherOneData'; var documents = ['banana', 'apple', 'monkey']; I successfully sent both a normal value and an a ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...

I am unable to load any HTML files in my VueJS iframe, except for the index.html located in the public

Within the template of my vue component, I am utilizing the following code: <iframe width="1000vw" height="600vh" src="../../public/myHtmlFile.html"></iframe> Unfortunately, the file specified in the src attribut ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Theme not being rendered properly following the generation of a dynamic component in Angular

I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file a ...