Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys I hope you are doing well , I need some help here,
I am trying to writte a script in php which retrieves data from a json url and save it to a txt file.

The json file has an array with three tables (i just want to receive only one table [data]),
so with the script that I wrotte indeed it took the data from the json url and exported to a txt file but the issue is that the data that I export in txt file are not passing json validator , I want the exported content to pass online json validator ,
any idea what I miss here and what should I do to fix the issue?

Many thanks in advance to everyone for your time and your help!

What I have tried:

PHP
<pre><?php
$url = 'my_url';


 
//read json file from url in php
$readJSONFile = file_get_contents($url);
 
//convert json to array in php
$table = json_decode($readJSONFile);


//print data.
var_dump($table->data);

$serialized = serialize($table->data);

file_put_contents('C:\\wamp64\\www\\script\\export.txt', $serialized);

//Retrieve the serialized string.
$fileContents = file_get_contents('C:\\wamp64\\www\\script\\export.txt');

//Unserialize the string back into an array.
$arrayUnserialized = unserialize($fileContents);

//End result.
var_dump($arrayUnserialized);



?>
Posted
Updated 16-Feb-22 4:36am
v2

Write a function to validate your json string like:
function jsonValidator($str=NULL) {
if (is_string($str)) {
	@json_decode($str);
	return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}

In your code call this method to check either json is valid or not, it will return you boolean value.
//read json file from url in php
$readJSONFile = file_get_contents($url);
 
if(jsonValidator($readJSONFile)) 
{
	//convert json to array in php
	$table = json_decode($readJSONFile);
	
	//..... rest of code
}
 
Share this answer
 
Comments
JasonTsoum77 11-Feb-22 7:55am    
Hi friend thanks for your time and your help, I wrotte the code but no errors returned from json url (I aslo test the json from url and no validator errors returned I should mentioned that at firts) but still the exported content to the txt file is not passing the json validator it reurns parse errors
I figure it out !!!

<pre><?php

$cache=dirname(_FILE_).'file.txt';

for($i=1; $i<30000; $i++){
$data=file_get_contents('url.$i);

$res=json_decode($data);
foreach($res as $key=>$value){
//print_r($value);
}

$res1=$res->data;
$res2= json_encode($res1,JSON_UNESCAPED_UNICODE);
print_r($res2);

$file=file_put_contents($cache,$res2, FILE_APPEND);

}
?>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900