nested JSON array to csv in PHP - php

How can I output this json to csv properly?
My json file pattern is like this:
{
"swimmers": [
{
"Province": "Ontario",
"Exemption": "S9,SB9,SM9",
"Code": "A,3,4",
"Level": "Level 8",
"ClassificationDate": "2020",
"RYEar": "2024",
"Status": "Registered",
"ID": "123456",
"FirstName": "John",
"LastName": "Doe",
"Gender": "M",
"AGE": null,
"DOB": "01/11/2000",
"Clubs": [
{
"Clubname": "Human Fish",
"Code": "ABC",
"Clubid": "300"
}
],
"Email": null,
"Language": "E",
"ChallengeData": null
}
//more entries with same pattern as first
],
"status": "OK",
"application": "SOme App API"
}
I had success to turn it into a csv with the code below but I'm unable to output the clubs field in the csv file, instead of showing the club, it just shows "Array()". I tried to fix that with the commented code but it doesn't solve the problem.
$csvFileName = 'converted.csv';
$json = 'myjson.json';
$data = file_get_contents($json);
$payload= json_decode($data);
$file_pointer = fopen($csvFileName, 'w');
if ($file_pointer){
foreach($payload['swimmers'] as $row) {
// $clubs = $row['Clubs'] ;
// if (is_array($clubs)){
// foreach($clubs as $c){
// fputcsv($file_pointer, $c);
// }
// }else{
fputcsv($file_pointer, $row);
}
}

Append each element of the Clubs field to $row, then remove the Clubs field.
foreach ($payload['swimmers'] as $row) {
foreach ($row['Clubs'] as $club) {
$row = array_merge($row, array_values($club));
}
unset($row['Clubs']);
fputcsv($file_pointer, $row);
}

Related

Getting data from nested arrays in json with php

I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2

Add data to JSON child array

This is my JSON file(database.json):
{
"doctors": [
{
"ID": "ahmadakhavan",
"pass": "1234",
"name": "Ahmad Akhavan",
"profilePic": "address",
},
{
"ID": "akramparand",
"pass": "1234",
"name": "Akram Parand",
"profilePic": "address",
}
],
"games": [
{
"ID": "shuttlefuel_1",
"locked": "0",
"logo": "gameLogo",
},
{
"ID": "birthdaycake",
"locked": "0",
"logo": "gameLogo",
}
],
"users": [
{
"ID": "alirezapir",
"prescribes": [
{
"doctorName": "doctor1",
"done": "yes",
"gameId": "wordschain"
},
{
"doctorName": "doctor2",
"done": "no",
"gameId": "numberlab"
}
],
"profilePic": "address"
},
{
"ID": "amirdibaei",
"pass": "1234",
"profilePic": "address"
}
]
}
I want to add a child under prescribes array for a specific ID.
Below is what I have done in my PHP code to do this:
<?php
$username = $_REQUEST['name'];
$data = $_REQUEST['data'];
//Load the file
$contents = file_get_contents('./database.json');
$arraydata = json_decode($data,true);
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true );
foreach($contentsDecoded['users'] as $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$item['prescribes'] = Array();
}
array_push($item['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
exit('0');
exit;
?>
If I echo $item['prescribes'] after the line array_push($item['prescribes'],$arraydata); I see data added to it, but the original file (database.json) won't show new added data.
(meaning that this new data is not added to $contentsDecoded)
You have to change foreach() code like below:-
foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
if($item['ID'] == $username){
$item['prescribes'][] = $arraydata; //assign new value directly
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit;
}
}
Change your foreach to change the $contentsDecoded array:
foreach($contentsDecoded['users'] as $key => $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$contentsDecoded['users'][$key]['prescribes'] = Array();
}
array_push($contentsDecoded['users'][$key]['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}

Problems iterating through an array

I'm having problems looking through the array data from a json file.
This is the code I have
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}
}
The problem I have is its only 'looking' at the last set of data and not all of it. if I put the barcode in twice I get the error This user is already in your contacts but if I put a new one in and then the existing barcode again it doesn't work.
I'm sure its something to do with the foreach loop but can not figure it out.
my json data is structured like this :
[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}
]
what I want to do is see if the barcode number already exists in the json file if it does show the error if it doesn't carry on with the rest of my code and add in the new data
For the second iteration, the $alreadyscanned will be set on a user that doesn't match the condition if one that has been scanned already came before it. Either reset the value of $alreadyscanned or use array to keep a list of errors.
$alreadyscanned = [];
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[$barcodejson] = 'This user is already in your contacts';
} else { do something}
}
foreach($alreadyscanned as $barcode => $error) {
var_dump($barcode. " :: " . $error);
}
Consider using break in your loop when you get into the if part: you don't want to continue once you find a duplicate:
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
} else { do something}
Now the dosomething could be unwanted here (depending on what it does). You may need to do that in a separate loop. Something like this:
$alreadyscanned= "";
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
}
}
if ($alreadyscanned=="") {
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
// do something
}
}
Lacking semicolons and stuff makes it harder to get the desired result.
Something like this might help you out on getting the data you want. Basically you can check the result of parsing by print_r-ing the json decoding process.
Then, you get a process result for each entry and, again, as a test, you can print the resulting array.
<?php
//Enter your code here, enjoy!
$json = '[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}]'
;
$barcode = '732580652913857773001'; //just an example this is set as a variable
$json_data = json_decode($json, true);
print_r($json_data);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[] = 'user ' . $data["Email"] .' is already in your contacts';
} else {
$alreadyscanned[] = 'This user '. $data["Email"] .' is not in your contacts';
}
}
print_r($alreadyscanned);
You need to use a function for that, so that you can use return when you find the needed barcode
function searchbarcode($json_data, $barcode)
{
foreach($json_data as $data)
{
if ( $data['Barcode'] == $barcode )
return true;
}
return false;
}
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
if(searchbarcode($json_data, $barcode)){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}

Get json object that matching maximum words from a string using php

I have a json response like this:
{
"status": 200,
"msg": "OK",
"result": {
"folders": [
{
"id": "3812454",
"name": ".subtitles"
},
{
"id": "3812455",
"name": ".videothumb"
}
],
"files": [
{
"name": "Angamaly Diaries HD.MP4.mp4",
"cblock": null,
"sha1": "fcc2c99f2db6e3e8a700c3247206a1c2148e14cb",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "713544705",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "PjUv5IYA2J8"
},
{
"name": "Take Off 2017.MP4.mp4",
"cblock": null,
"sha1": "2fe7fb4d45322a085d41239d6429d1cc8e94e2ce",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "954148848",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "BIBcjWqF0_I"
},
{
"name": "Rangoon 2017 Tamil.MP4.mp4",
"cblock": null,
"sha1": "c685e7c11636982860ae7f34b671a20fc746feee",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "779899588",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "00D7GzP6mls"
},
{
"name": "The Zookeeper’s Wife 2017.MP4.mp4.mp4",
"cblock": null,
"sha1": "a143faafbd8a6eaf2276f25cd642ac3019d71ffc",
"folderid": "3812453",
"upload_at": "1510256266",
"status": "active",
"size": "550126461",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "bwUhqbiJJWQ"
}
]
}
}
And I have a string with this text:
"Watch Take Off 2017 Malayalam Full Movie Online Free"
Now I need to get the linkextid of
"name": "Take Off 2017.MP4.mp4"
from JSON response. There is one more thing that I have so much similar data on the JSON response, but I need to the get name that matches maximum words from string using PHP.
<?php
$json_data='{"status":200,"msg":"OK","result":{"folders":[{"id":"3812454","name":".subtitles"},{"id":"3812455","name":".videothumb"}],"files":[{"name":"Angamaly Diaries HD.MP4.mp4","cblock":null,"sha1":"fcc2c99f2db6e3e8a700c3247206a1c2148e14cb","folderid":"3812453","upload_at":"1510255141","status":"active","size":"713544705","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"PjUv5IYA2J8"},{"name":"Take Off 2017.MP4.mp4","cblock":null,"sha1":"2fe7fb4d45322a085d41239d6429d1cc8e94e2ce","folderid":"3812453","upload_at":"1510255141","status":"active","size":"954148848","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"BIBcjWqF0_I"},{"name":"Rangoon 2017 Tamil.MP4.mp4","cblock":null,"sha1":"c685e7c11636982860ae7f34b671a20fc746feee","folderid":"3812453","upload_at":"1510255141","status":"active","size":"779899588","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"00D7GzP6mls"},{"name":"The Zookeeper’s Wife 2017.MP4.mp4.mp4","cblock":null,"sha1":"a143faafbd8a6eaf2276f25cd642ac3019d71ffc","folderid":"3812453","upload_at":"1510256266","status":"active","size":"550126461","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"bwUhqbiJJWQ"}]}}';
$data=json_decode($json_data,true);
$files=$data['result']['files'];
$search="Watch Take Off 2017 Malayalam Full Movie Online Free";
$search_array=explode(' ',$search);
foreach($search_array as $key=>$row){
$search_array[$key]=trim($row);
}
$match=[];
foreach($files as $key=>$row){
$match_count=0;
foreach($search_array as $s){
if(preg_match('/'.$s.'/',$row['name'])){
$match_count+=1;
}
}
$match[$key]=$match_count;
}
rsort($match);
print_r($files[$match[0]]['linkextid'])
?>
Not the best solution in the world but this should work:
<?php
function compare_strings($s1, $s2) {
$s1Words = explode(' ', $s1);
$s2Words = explode(' ', $s2);
$wordCount = 0;
foreach ($s1Words as $word) {
if ( strpos($s2Words, $word) ) {
$wordCount++;
}
}
return $wordCount;
}
function get_movie_linkextid($data, $name) {
$bestMatchIndex = 1;
$bestMatchScore = 0;
foreach ($data['result']['files'] as $i => $movie) {
$currentScore = compare_strings($movie['name'], $name);
if ($currentScore > $bestMatchScore) {
$bestMatchScore = $currentScore;
$bestMatchIndex = $i;
}
}
return $data['result']['files'][$bestMatchIndex]['linkextid'];
}
$data = json_decode($yourJsonData, true);
$name = "Watch Take Off 2017 Malayalam Full Movie Online Free";
echo get_movie_linkextid($data, $name);
?>
The code just parses your JSON into a variable and than goes through all the 'files' comparing their names with the string you provided the determine the best match. After that it just return the linkextid.
I Didn't tested this code but the important is to get the idea since you will have to adapt it to be more generic anyway.

Search file contents of a json file in PHP and return results

I am trying to create a search a function in php which searches for the data contained inside a Json file. I am able to do this for a normal text file which returns a list of results based on what has been entered in the search field which returns closet match. However does not work when doing this same for a json file and does not return anything.
search.php
if (isset($_POST) && isset($_POST['txt'])) {
$search = $_POST['txt'];
$file = file('data/contacts.json');
$found = false;
$jsonData = json_decode($file, true);
foreach ($jsonData as $line) {
if (strpos($line, $search) !== false) {
$found = true;
echo $line;
}
}
if (!$found) {
echo 'No match found';
}
}
contacts.json
[
{
"id": 3,
"forename": "John",
"surname": "Smith",
"email": "j#hotmail.com",
"address": "addresss",
"telephone": "01232302323"
},
{
"id": 4,
"forename": "Keith",
"surname": "Miller",
"email": "K#hotmail.com",
"address": "ssdsds",
"telephone": "01232302323"
},
{
"id": 5,
"forename": "Doug",
"surname": "Howard",
"email": "d#hotmail.com",
"address": "test",
"telephone": "01232302323"
},
{
"id": 2,
"forename": "r",
"surname": "r",
"email": "email#gmail.com",
"address": "test",
"telephone": "01232302323"
}
]
Change this line $jsonData = json_decode($file, true); to
$jsonData = json_decode(json_encode($file),true);

Categories