How to convert JSON to HTML using PHP? - php

I am trying to do the inverse function of the response received in this post: [Post][1]
[1]: https://stackoverflow.com/a/23427469/19867306
#scozy shows us a function to transform an html text to a JSON model. I need to transform the same JSON model to HTML again.
The function shared by #scozy is:
function html_to_obj($html) {
$dom = new DOMDocument();
$dom->loadHTML($html);
return element_to_obj($dom->documentElement);
}
function element_to_obj($element) {
$obj = array( "tag" => $element->tagName );
foreach ($element->attributes as $attribute) {
$obj[$attribute->name] = $attribute->value;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
$obj["html"] = $subElement->wholeText;
}
else {
$obj["children"][] = element_to_obj($subElement);
}
}
return $obj;
}
$html = <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<title> This is a test </title>
</head>
<body>
<h1> Is this working? </h1>
<ul>
<li> Yes </li>
<li> No </li>
</ul>
</body>
</html>
EOF;
header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);
The output of the function is this:
{
"tag": "html",
"lang": "en",
"children": [
{
"tag": "head",
"children": [
{
"tag": "title",
"html": " This is a test "
}
]
},
{
"tag": "body",
"html": " \n ",
"children": [
{
"tag": "h1",
"html": " Is this working? "
},
{
"tag": "ul",
"children": [
{
"tag": "li",
"html": " Yes "
},
{
"tag": "li",
"html": " No "
}
],
"html": "\n "
}
]
}
]
}
I was thinking of making a function that, using the help of json_decode, transforms the json into an object and then makes use of a foreach and then makes a recursive call to the same function. At the moment my mind is all mixed up and it would be a great help if you could give me a hand.
My mind:
function json_to_html($json) {
$html = json_decode($json);
foreach ($html as $key => $item) {
// Something :C
}
}
$json = '{ "tag": "html", "lang": "en", "html": "\r\n", "children": [ { "tag": "head", "html": "\r\n ", "children": [ { "tag": "title", "html": " This is a test " } ] }, { "tag": "body", "html": "\r\n ", "children": [ { "tag": "h1", "html": " Is this working? " }, { "tag": "ul", "html": "\r\n ", "children": [ { "tag": "li", "html": " Yes " }, { "tag": "li", "html": " No " } ] } ] } ] }';
json_to_html($json);

I solved the question as follow:
function json_to_html($json) {
$html = "";
$param = "";
foreach ($json as $key => $value) {
if (is_numeric($key) || $key == 'children') {
$html = $html . json_to_html($value);
} else {
if ($key == 'tag') {
$tag = "<$value [param]>[html]</$value>";
continue;
} else if ($key == 'html') {
$tag = str_replace('[param]',$param,$tag);
$html = str_replace('[html]',$value,$tag);
continue;
} else {
$param = $param . $key . ' = "' . $value . '"';
continue;
}
}
}
return $html;
}
Note: the json is decoded previously

Related

How to display info on double array JSON (php)

I would like to know how to display the information below.
Link (JSON):
https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents
What I wish to have:
"teams": [
[
{
"provider": "psn",
"username": "Germania1992"
},
{
"provider": "psn",
"username": "killzoneprofi"
},
{
"provider": "psn",
"username": "ayozetf87"
},
{
"provider": "psn",
"username": "Seith911"
},
{
"provider": "psn",
"username": "domibreu92"
}
],
[
{
"provider": "psn",
"username": "Thejuankarboy"
},
{
"provider": "psn",
"username": "Gamermad101"
},
{
"provider": "psn",
"username": "Izdrap"
},
{
"provider": "psn",
"username": "Guerra_sv"
},
{
"provider": "psn",
"username": "TriX_FollOoW_YT"
}
]
],
I want to display the nicks of the different teams
Example: Team 1 = Germania1992, killzoneprofi, ayozetf87, Seith911,
domibreu92
Thanks
You will have to do a double foreach that for sure.
<?php
// Get the json of the team
$team = team("https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents");
// Display the teams info
foreach($team as $nb=>$data){
echo "Team $nb<br />";
foreach($data as $key=>$value){
echo "Provider: ".$value->provider."<br />";
echo "Username: ".$value->username."<br />";
}
echo "<hr>";
}
// Returns the team array of the json
function team($jsonURL){
$content=file_get_contents($jsonURL);
$data=json_decode($content);
return $data->data->teams;
}
?>
You could increment the team number by 1 to avoid the first being 0
The above will display the below screenshot (You can format the output as you please)
$result = [];
$counter = 0;
dump($array = json_decode(file_get_contents('https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents')));
dump($t = array_column((array)$array, 'teams'));
foreach ($t as $r) {
foreach ($r as $p) {
$counter++;
foreach ($p as $value){
$result["team$counter"][] = $value->username;
}
}
}
var_dump($result);

How to make output json array with php?

I had searched the answer but there's no solution for my problem.
How make output like this?
Thanks in advance
I want out this below
Title: First Title
Tags: tag-a-1, tag-a-2,tag-a-3
Title: Second Title
Tags: tag-b-1, tag-b-2, tag-b-3
Title: Third Title
Tags: tag-c-1, tag-c-2, tag-c-3
file.json
{
"videos": [
{
"title": "First Title",
"tags": [
{
"tag_name": "tag-a-1"
},
{
"tag_name": "tag-a-2"
},
{
"tag_name": "tag-a-3"
}
],
"publish_date": "2016-09-12 16:40:14"
},
{
"title": "Second Title",
"tags": [
{
"tag_name": "tag-b-1"
},
{
"tag_name": "tag-b-2"
},
{
"tag_name": "tag-b-3"
}
],
"publish_date": "2016-09-12 16:40:14"
},
{
"title": "Third Title",
"tags": [
{
"tag_name": "tag-c-1"
},
{
"tag_name": "tag-c-2"
},
{
"tag_name": "tag-c-3"
}
],
"publish_date": "2016-09-12 16:40:14"
}
]
}
output.php
<?php
ini_set('display_errors', 1);
$html = "file.json";
$html = file_get_contents($html);
$videos = json_decode($html, true);
foreach ($videos['videos'] as $video) {
$title = $video['title'];
foreach ($video['tags'] as $tags) {
$tags = $tags['tag_name'];
echo 'Title: ' . $title . '<br />';
echo 'Tags: ' . $tags . ', <br /><br />';
}
}
Your second iteration seems to be wrong. You should print title/tags in your first loop instead.
foreach ($videos['videos'] as $video) {
$title = $video['title'];
$tags = array(); // reset it every new item to avoid race-condition on empty one.
foreach ($video['tags'] as $tags) {
$tags[] = $tags['tag_name'];
// ^ also add new elements here
}
echo 'Title: ' . $title . '<br />';
echo 'Tags: ' . implode(',', $tags) . '<br /><br />';
// ^ also join your tags
}
Try using the json_decode function. That seems the way to go.
http://php.net/manual/en/function.json-decode.php
I've linked the docs in for you. Best of luck.

Select individual column json in php

{
"responseData": {
"results": [
{
"title": "sobig",
"titleNoFormatting": "test",
},
{
"title": "test 2 ",
"titleNoFormatting": "test 2sd",
},
{
"title": "asdasdasda",
"titleNoFormatting": "asdasdasd",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
.
.
.
.
{
"title": "last thing",
"titleNoFormatting": "sada",
}
],
I have json files like this.
for($i=$veri1; $i <= $veri2; $i++) {
$uri = "http://test.com/json/".$i."/0";
$json = json_decode(file_get_contents($uri));
if($json->data->price >= $nakit && $json->data->odds >= $oran)
{
I'm getting some data with this code correctly from another json file.
i want get data from first json code, if "title" == "sobig" . How can I do that.
$json->responseData->results->title == sobig is not working. How can I get data if title is sobig
$json= json_decode($response, true);
foreach ($json['responseData']['results'] as $key => $value) {
if ($value == 'sobig') {
// found it
}
}
Try this example to see if this may fix your issue.
<?php
$json = '{ "responseData": {
"result" : [
{ "title": "sobig" , "titleNo":"test"},
{ "title": "loco" , "titleNo":"test"},
{ "title": "tom" , "titleNo":"test"}
]
}}';
$jsonDecoded = json_decode($json);
foreach ($jsonDecoded->responseData->result as $key => $value) {
var_dump($value); echo '<br>';
if($value->title == 'sobig'){
echo "we did it!!";
echo "<br>";
}
}
?>
I place a couple of var dumps so you can see the stucture of your object and why you need to use the foreach

Accessing data in a multidimensional JSON object

I have the following JSON object returned from an API call in the $result variable, and my problem is that I need to access the "name" item in each list, but it doesn't work
{
"status": "success",
"data": {
"lists": [
{
"id": "0032",
"name": "Stan",
"status": "active",
},
{
"id": "0043",
"name": "David",
"status": "active",
},
{
"id": "2323",
"name": "Robert",
"status": "pending",
}
]
}
}
Code :
if (isset($result)) {
$json_object = json_decode($result, true);
echo $json_object['status'];
echo $result;
if ($json_object['status'] == 'success') {
$json_object2 = $json_object['data'];
foreach ($json_object['data'] as $key => $value){
foreach ($value as $key2 => $value2){
echo $key2 . " : " . $value2 . "</br>";
}
}
} else {
echo $json_object['data'];
}
}
Try something like this
<?php
$result = '{"status":"success","data":{"lists":[{"id":"0032","name":"Stan","status":"active"},{"id":"0043","name":"David","status":"active"},{"id":"2323","name":"Robert","status":"pending"}]}}';
$json_object = json_decode($result, true);
foreach($json_object['data']['lists'] as $item)
{
echo $item['name']."<br>";
}
?>

How to retrieve values from multilevel json

Im trying to get the values from the various sections of this json entry.
{
"gallery_show": "1",
"gallery": {
"path": ["images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg"],
"title": ["", "", "", "", "", ""],
"caption": ["", "", "", "", "", ""],
"thumb": ["\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg"]
},
"videos_show": "1",
"videos": {
"title": ["Arnie", "Arnie", "Arnie", "Arnie", "Arnie"],
"sharelink": ["http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY"]
},
"attachments_show": "1",
"attachments": {
"path": ["images\/slide2.jpg", "images\/slide1.jpg"],
"title": ["Attchment", "Attchment"],
"caption": ["Attachment Description", "Attachment Description"]
},
"links_show": "1",
"links": {
"title": ["Link1", "Link2"],
"httplink": ["http:\/\/www.mydomain.com", "http:\/\/www.mydomain.com"],
"targetlink": ["_blank", "_blank"]
}
}
If i use this method
$entries= json_decode($this->item->entries);
and then i echo this
echo $entries->gallery_show;
I get the desired result = 1
But how do i now get the things beneath it if gallery_show=1 and display them as values i can use inside my php?
Any help for this old brain would be much appreciated.
Cheers in advance
Jonny
You could do somewhat like this...
$arr = json_decode($json);
foreach($arr as $k=>$v)
{
if($k=='gallery_show' && $v==1)
{
foreach($arr->gallery->path as $path)
{
echo "<img src=$path />";
}
break;
}
}
Demo
Code update..
$arr = json_decode($json);
$i=0;
foreach($arr as $k=>$v)
{
if($k=='gallery_show' && $v==1)
{
foreach($arr->gallery as $gall)
{
echo "Title :".$arr->gallery->title[$i]."<br/>";
echo "Caption :".$arr->gallery->caption[$i]."<br/>";
echo "Thumbnail :".$arr->gallery->thumb[$i]."<br>";
echo "<img src=".$arr->gallery->path[$i]." /><br>";
$i++;
}
break;
}
}
Demo

Categories