How to programmatically edit JSON-LD in 'script' elements? - javascript

I have several HTML files on my server that contain JSON-LD script elements. I'm looking for an easy way to update specific elements without physically going into each file, changing the code, and re-saving it.
Specifically, I would like to programmatically loop through each file, find the datePosted property and update its value to the current date, then save the file on my server.
I'm mostly comfortable using PHP and I've done something like this with HTML files, but never tried updating JSON-LD before.
Wondering if anyone knows how to do this with JavaScript or PHP. If not could someone point me in the right direction of a good parser that works with JSON-LD?
Sample JSON-LD:
{
"#context": "http://schema.org",
"#type": "JobPosting",
"datePosted": "2018-01-23"
}

This was pretty easy, just needed to use json_decode and json_encode to make it work:
$file = "file-path-to-json-ld";
$string = file_get_contents($file); // pulls the file
$json = json_decode($string, true); //creates a searchable array
var_dump($json); // just to see what elements and values are in the decoded array
$json['element-name-in-json-ld'] = "new-value-for-element"; //change any value you like
$updatedString = json_encode($json, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); //re-encode backing into json
file_put_contents($file, $updatedString); // put file back

Related

PHP json to a JavaScript variable inside an HTML file

I write the following script that creates a nice JSON of all the images under the current folder:
<?php
header('Content-type: application/json');
$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
$files = glob(''.$dirname.'/*');
$images = preg_grep($pattern, $files);
$output->{$dirname} = $images;
}
echo json_encode($output, JSON_PRETTY_PRINT);
?>
I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.
So the question is how can I get the PHP data into a javascript variable?
<html>
...
<body>
<script src="images.php"></script>
<script type="text/javascript">
// Desired: Get access to JSON $output
</script>
...
<div>
<img ... >
</div>
</body>
</html>
I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)
you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is
// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
var images = "<?= $images ?>";
</script>
I won't guarantee that this js line is going to work but you get the idea)
P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is
I took #Zeusarm advice and just used ajax (and jquery) instead.
For others need a reference:
Nothing to change in PHP script in the original post.
Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Make a GET request like this:
<script type="text/javascript">
var images = ''
$.get('images.php',function (jsondata) {
images = jsondata
});
I am sure this is not the cleanest code but it works :)

Use PHP to extract data from an object literal in the middle of a JavaScript program

I have a JS file with the following assignment of an object literal to a variable in it.
var data = {
title:"My webpage",
};
I want to access this JS file from PHP to read this data so I can output it into HTML.
Since this is not JSON, the following does not work.
$str = file_get_contents("data/data.js");
$object = json_decode($str, true);
echo $object['title'];
How would I access that file and write out the 'title' to HTML using a PHP file?
Is there a reason you can't use a .json file?
If not a really quick and easy/dirty solution would be to have a file like:
data.json
{
"title":"My webpage"
}
And then just get it the way you are trying to.

Finding all PHP functions in a file

I want to find all functions in a file - thats no problem:
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
The problem is that if there are Javascript functions, they will get in the scheme, too.
Is it even possible to get only PHP-functions.
One indicator would be the <script>-Tag, but I have no Idea how to only track functions, which are not surounded by the script-Tag!
Thank you!
I had THE idea 2 seconds after writing the question.
$data = file_get_contents($file);
$data = preg_replace("/<script[^>]*>[\s\S]*?<\/script>/", "", $data);
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
Just delete all the <script>-Tags!
If you would need them later, you also could save them (instead of replacing them) and add them later!
Just if someone else will have the same problem!
One option would be to remove all <script>...</script> tags before processing, but this assumes that you will only have JavaScript in these tags directly in the file. If you have a function or a library that generates HTML for you, it is possible for you to output JavaScript code without explicitly having the <script>...</script> tags in your PHP document. The issue is that you are using pattern matching, which can lead to an array of false positives.
To remove these false positives all together, you could use the PHP ReflectionFunction class to determine which functions are defined in PHP and which are not. Once you have an array of possible function names, use the following:
$data = file_get_contents($file);
$outputData;
$validMatches=array();
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
foreach($outputData[1] as $match) {
$isValid=true;
try {
$reflection = new \ReflectionFunction($match);
} catch (\ReflectionException $e) {
$isValid=false;
}
if($isValid == true) {
$validMatches[]=$match;
}
}
This is more verbose but it will guarantee that you will get a list of only PHP function names.

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Parsing CDATA from Javascript

This is my first post and I'm sorry if I'm doing it wrong but here we go:
I've been working on a project that should scrape values from a website. The values are variables in a javascript array. I'm using the PHP Simple HTML DOM and it works with the normal scripts but not the one stored in CDATA-blocks. Therefore, I'm looking for a way to scrape data within the CDATA-block. Unfortunately, all the help I could find was for XML-files and I'm scraping from a HTML file.
The javascript I'm trying to scrape is a follows:
<script type="text/javascript">
//<![CDATA[
var data = [{"value":8.41,"color":"1C5A0D","text":"17/11"},{"value":9.86,"color":"1C5A0D","text":"18/11"},{"value":7.72,"color":"1C5A0D","text":"19/11"},{"value":9.42,"color":"1C5A0D","text":"20/11"}];
//]]>
</script>
What I need to scrape is the "value"-variable in the var data.
The problem was that I tried to replace the CDATA string on an object.
The following code works perfectly :-)
include('simple_html_dom.php');
$lines = file_get_contents('http://www.virtualmanager.com/players/7793477-danijel-pavliuk/training');
$lines = str_replace("//<![CDATA[","",$lines);
$lines = str_replace("//]]>","",$lines);
$html = str_get_html($lines);
foreach($html->find('script') as $element) {
echo $element->innertext;
}
I will provide you with more information if needed.
A decent HTML parser shouldn't require Javascript to be wrapped in a CDATA block. If they're throwing it off, just remove them from the HTML before parsing, doing something like this:
Download the HTML file into a string, using file_get_contents() or cURL if your host disabled HTTP support in that function.
Get rid of the //<![CDATA[ and //]]> bits using str_replace()
Parse the HTML from the cleaned string using Simple DOM's str_get_html()
Process the DOM object as before.

Categories

Resources