Okay so I'm playing around with php at the moment. I have a .html file and a .php file. The .html file contains a textarea. The .php file contains some functions that messes around with the user's typed json string. I know how to output php onto the webpage. I want to output the WHOLE json script onto the textarea. Basically in the .php file, I want to convert the json to a string, and pass that string into the .html's textarea.
This is the json:
{
"destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
"origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "3.0 mi",
"value" : 4855
},
"duration" : {
"text" : "22 mins",
"value" : 1311
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried using json_encode() but got errors because of the quotations marks being out of place so Im wondering if theres an easier way to convert the whole json to a string .
If you are not getting the line returns and tabs for formatting you can use my pretty json print function, which will add tabs and line returns to the json data.
function PrettyJson($json) {
$tc = 0; //tab count
$r = ''; //result
$q = false; //quotes
$t = "\t"; //tab
$nl = "\n"; //new line
for($i=0;$i<strlen($json);$i++){
$c = $json[$i];
if($c=='"' && $json[$i-1]!='\\') $q = !$q;
if($q){
$r .= $c;
continue;
}
switch($c){
case '{':
case '[':
$r .= $c . $nl . str_repeat($t, ++$tc);
break;
case '}':
case ']':
$r .= $nl . str_repeat($t, --$tc) . $c;
break;
case ',':
$r .= $c;
if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);
break;
case ':':
$r .= $c . ' ';
break;
default:
$r .= $c;
}
}
return $r;
}
Then you just echo it
echo '<textarea>'.PrettyJson( $json ).'</textarea>';
Basically what it does is given json string like this
{"one":[1,2,3],"two":{"three":3}}
It will make it like this ( or similar )
{
"one" : [1,2,3],
"two" : {
"three" : 3
}
}
Typically I just use it for display so I am not sure right off if you need to remove the white space when decoding it.
If the PHP holds also the HTML then just use htmlspecialchars() to escape the special characters that would be problematic between the <textarea> tag.
Small example of a PHP file:
<?php
// Get the json value from a previous POST or set a default value.
$json = isset($_POST['json']) ? $_POST['json'] : '{
"destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
"origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "3.0 mi",
"value" : 4855
},
"duration" : {
"text" : "22 mins",
"value" : 1311
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}';
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div><!-- because form elements should not be direct childs of the form -->
<label for="json">Type your JSON:</label>
<br />
<textarea name="json" rows="25" cols="84"><?php echo htmlspecialchars($json); ?></textarea>
<br />
<br />
<input type="submit" value="submit" />
</div>
</form>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working with a charity who need their own specific CMS to post blogs. I have set up QuillJS which works well and output JSON.
How do I convert JSON data back to HTML with the relevant tags? I need the HTML tags to be shown too such as '<p>Hello</p>'. I can get the JSON data via php mysql but don't know how to show the tags.
For example how to I convert the following
JSON
{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}
To
HTML
<html>
<h2>EditorJS</h2>
<p>Hey. Meet the new Editor. On this page you can see it in action — try to edit this text.</p>
</html>
Many thanks in advance for any help!
Here's a complete solution. Each step is mentioned in the comments:
<?php
$jsonData = '{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}';
//decode the JSON
$data = json_decode($jsonData);
//loop through the blocks
foreach ($data->blocks as $block)
{
$start = "";
$end = "";
//detect the element type and set the HTML tag string
switch ($block->type)
{
case "header":
$start = "<h2>";
$end = "</h2>";
break;
case "paragraph":
$start = "<p>";
$end = "</p>";
break;
}
//output the final HTML for that block
echo $start.$block->data->text.$end;
}
Demo: http://sandbox.onlinephpfunctions.com/code/ab862de1113d8744bc2d9463f7a7df2496491110
So you need to first decode the JSON so php can use it as an array and loop through foreach to display.
$someJSON = '{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}';
Now we decode and display
$someData = json_decode($someJSON, true);
//--> Create an empty variable to hold the display text...
$output = null;
//--> Run foreach loop, we can see the associative keys in the array, this gives
//--> us everything we need to pull the data out and display it properly...
//--> loop through the converted arrays first child 'blocks' and get the values
foreach ($someData['blocks'] as $value) {
//--> If the 'type' === 'header' wrap value -> ['data'] -> ['text'] in <h2> tag
if($value['type'] === "header"){
$output .= '<h2>'.$value['data']['text'].'</h2>';
}
//--> If the 'type' === 'paragraph' wrap value -> ['data'] -> ['text'] in <p> tag
if($value['type'] === "paragraph"){
$output .= '<p>'.$value['data']['text'].'</p>';
}
}
In your HTML output the variable within php tags to display the concatenated HTML held within $output
<html>
<div id="my_id">
<span class="my_class">
<?=$output?> or <?php echo $output; ?>
</span>
</div>
</html>
http://sandbox.onlinephpfunctions.com/code/e8fdb5b84af5346d640e92e6788e5c2836b9ad07
I'd like to print this json
i can print the first part with the actions
PHP:
$print= json_decode($output_data);
foreach($print->actions as $mydata)
{
echo $mydata->ID.'<br><br>';
}
JSON:
{
"actions": [
{
"ID":"Search",
"name":"Select"
}
],
"content": {
"TEST": "false",
"nickname": "brad"
}
}
but i cant print the content part to show the TEST and nickname content.
Can you please help me ?
Thanks
In the assumption you Json format is like this:
{
"actions" : [{
"ID" : "Search",
"name" : "Select"
}
],
"content" : {
"TEST" : "false",
"nickmane" : "brad"
}
}
You can do it like in next example:
$print= json_decode($output_data);
// Print all actions IDs:
foreach($print->actions as $mydata)
{
echo $mydata->ID . '<br><br>';
}
// Print TEST.
echo "TEST: " . $print->content->TEST . " Nickname: " . $print->content->nickname;
Also, if you need to dump all the JSON, try this:
$print = json_decode($output_data);
print_r($print);
Or this:
$print = json_decode($output_data);
$output = print_r($print, true);
echo $output;
You can read more about print_r() and other ways to dump variables here: http://php.net/manual/es/function.print-r.php
You can do it quite simply like this:
$print= json_decode($output_data);
echo $print->content->TEST;
echo "<br/>";
echo $print->content->nickmane;
The difference from the "actions" is that "actions" is an array whereas "content" is an object, so you don't need a loop.
Click here to run a demo of this code
Your JSON is not a valid format. I appears your JSON should be the following to do what you want:
{
"actions" : [{
"ID" : "Search",
"name" : "Select"
}
],
"content" : {
"TEST" : "false",
"nickmane" : "brad"
}
}
I am trying to get a data that is in an array inside another array, I did a search by the forum and google and I made several attempts without success.
It seems like an easy catch but I'm breaking my head all day and I can not.
I'm leaving below my JSON code and my last attempt to pass to PHP.
Thankful.
CODE JSON:
{
"ordens_de_servico": [
{
"oser_numero_os": 23932944,
"oser_nome_solicitante": "ED PI - CAMPO MAIOR",
"oser_dt_abertura": "27/03/2018",
"oser_pontos_refer_endereco": null,
"oser_observ_reclamacao": null,
"oser_prioridade": null,
"servico": {
"serv_cod_servico": 60,
"serv_descr_servico": "CORTE POR DEBITO"
},
"cliente": {
"nome": "ANTONIO WELTON DA SILVA OLIVEIRA",
"telefone": " "
},
"unidade_consumidora": {
"unid_ident_uc": 10945024,
"logr_nome_logr_expandido": null,
"medidor": "A2006171",
"latitude": " -4.711808",
"longitude": "-41.793455"
},
"faturas": [
{
"total_fatura": "23.01"
},
{
"total_fatura": "17.88"
},
{
"total_fatura": "23.01"
},
{
"total_fatura": "21.9"
},
{
"total_fatura": "22.92"
}
]
}
]
}
CODE PHP
<?php
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);
$os = $json_data['ordens_de_servico'][0]['oser_numero_os']. PHP_EOL;
$data = $json_data['ordens_de_servico'][0]['oser_dt_abertura']. PHP_EOL;
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
echo $os."<p>";
echo $data."<p>";
echo $cod_serv."<p>";
echo $total_fatura."<p>";
?>
I tried looping unsuccessfully on the fatura
$json_data = json_decode($json,false);
foreach ( $json_data->ordens_de_servico as $valor){
echo 'FATURA:'.$valor->faturas->total_fatura."<p>".PHP_EOL;
echo PHP_EOL;
}
At a minimum, you are missing the [0] on these two lines:
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
They need to be:
$cod_serv = $json_data['ordens_de_servico'][0]['servico']['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico'][0]['faturas'][0]['total_fatura']. PHP_EOL;
Example of looping through elements in arrays:
foreach($json_data['ordens_de_servico'] as $key => $value){
echo $value["oser_numero_os"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
}
}
I'm trying to get data into the tabular format by invoking JSON data into PHP code.
JSON code written to use for converting into tabular format.
[
{
"#":"3586 "
"Project" :"SSMT",
"Tracker" :"Maintenance",
"Status" : "To Do"
"Subject" : "Test the following scenario and provide the relevant scripts in centos7"
"Author" : "Anil K"
"Assignee" : "SSMT Group"
},
{
"#" :"3517"
"Project" : "SSMT"
"Tracker" : "Improvement"
"Status" : "In Progress"
"Subject" : "Image server daily backup"
"Author" : "Lakshmi G"
"Assignee" : "Pooja S"
},
{
"Project" : "SSMT"
"Tracker" : "Improvement"
"Status" : "In Progress"
"Subject" : "setup openstack all-in-one in centos7 instance on ORAVM1 box."
"Author" : "Anil K"
"Assignee" : "Bhanuprakash P"
}
]
The below php code is written to fetch the above JSON data.
<!DOCTYPE html>
<html lang = "en-US">
<?php
$url = 'data.json';
$data = file_get_contents($url);
$characters = json_decode($data);
echo $characters[0]->name;
foreach ($characters as $character) {
echo $character->name . '<br>';
}
?>
<table>
<tbody>
<tr>
<th>#</th>
<th>Project</th>
<th>Tracker</th>
<th>Status</th>
<th>Subject</th>
<th>Author</th>
<th>Assignee</th>
</tr>
<?php
foreach ($characters as $character) {
echo '<tr>'
echo '<td>' . $character-># . '</td>';
echo '<td>' . $character->project . '</td>';
echo '<td>' . $character->tracker . '</td>';
echo '<td>' . $character->status . '</td>';
echo '<td>' . $character->subject . '</td>';
echo '<td>' . $character->author . '</td>';
echo '<td>' . $character->assignee . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</html>
I received following error
PHP Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /var/www/html/tabularformat.php on line 34
can anyone suggest othis? ?
after adding ; at the end of each 'echo' statement. also getting the same error. please find it.
I recommend using true as the second parameter to form array elements.
Your json is invalid (I fixed it in my code)
You need to access the keys case-sensitively.
Check that an element exists before trying to access it.
Code: (Demo)
$json='[
{
"#":"3586 ",
"Project" :"SSMT",
"Tracker" :"Maintenance",
"Status" : "To Do",
"Subject" : "Test the following scenario and provide the relevant scripts in centos7",
"Author" : "Anil K",
"Assignee" : "SSMT Group"
},
{
"#" :"3517",
"Project" : "SSMT",
"Tracker" : "Improvement",
"Status" : "In Progress",
"Subject" : "Image server daily backup",
"Author" : "Lakshmi G",
"Assignee" : "Pooja S"
},
{
"Project" : "SSMT",
"Tracker" : "Improvement",
"Status" : "In Progress",
"Subject" : "setup openstack all-in-one in centos7 instance on ORAVM1 box.",
"Author" : "Anil K",
"Assignee" : "Bhanuprakash P"
}
]';
$characters = json_decode($json,true);
foreach ($characters as $character) {
echo '<tr>';
echo '<td>',(isset($character['#'])?$character['#']:''),'</td>';
echo '<td>',(isset($character['Project'])?$character['Project']:''),'</td>';
echo '<td>',(isset($character['Tracker'])?$character['Tracker']:''),'</td>';
echo '<td>',(isset($character['Status'])?$character['Status']:''),'</td>';
echo '<td>',(isset($character['Subject'])?$character['Subject']:''),'</td>';
echo '<td>',(isset($character['Author'])?$character['Author']:''),'</td>';
echo '<td>',(isset($character['Assignee'])?$character['Assignee']:''),'</td>';
echo '</tr>';
}
Output:
<tr>
<td>3586 </td>
<td>SSMT</td>
<td>Maintenance</td>
<td>To Do</td>
<td>Test the following scenario and provide the relevant scripts in centos7</td>
<td>Anil K</td>
<td>SSMT Group</td>
</tr>
<tr>
<td>3517</td>
<td>SSMT</td>
<td>Improvement</td>
<td>In Progress</td>
<td>Image server daily backup</td>
<td>Lakshmi G</td>
<td>Pooja S</td>
</tr>
<tr>
<td></td>
<td>SSMT</td>
<td>Improvement</td>
<td>In Progress</td>
<td>setup openstack all-in-one in centos7 instance on ORAVM1 box.</td>
<td>Anil K</td>
<td>Bhanuprakash P</td>
</tr>
Otherwise, you can use "encapsulation" to access the # object.
$characters = json_decode($json);
foreach ($characters as $character) {
echo '<tr>';
echo '<td>',(isset($character->{'#'})?$character->{'#'}:''),'</td>';
// ...
From the manual:
Example #2 Accessing invalid object properties
Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
I'm trying to extract the main table from a website, convert it to JSON, but the tables before the one I want are obstructing the code I'm using. The code I'm using:
<?php
$singles_chart_url = 'http://www.mediabase.com/mmrweb/allaboutcountry/Charts.asp?format=C1R';
// Get the mode from the user:
$mode = $_GET['chart'];
// This is an array of elements to remove from the content before stripping it:
$newlines = array("\t", "\n", "\r", "\x20\x20", "\0", "\x0B");
switch($mode)
{
// They want the Singles chart, or haven't specified what they want:
case 'singles':
case '':
default:
$content = file_get_contents($singles_chart_url);
$start_search = '<table width="100%" border="0" cellpadding="2" cellspacing="2">';
break;
}
$content = str_replace($newlines, "", html_entity_decode($content));
$scrape_start = strpos($content, $start_search);
$scrape_end = strpos($content, '</table>', $scrape_start);
$the_table = substr($content, $scrape_start, ($scrape_end - $scrape_start));
// Now loop through the rows and get the data we need:
preg_match_all("|<tr(.*)</tr>|U", $the_table, $rows);
// Set the heading so we can output nice XML:
switch($_REQUEST['format'])
{
case 'json':
default:
header('Content-type: application/json');
$count = 0;
foreach($rows[0] as $row)
{
// Check it's OK:
if(!strpos($row, '<th'))
{
// Get the cells:
preg_match_all("|<td(.*)</td>|U", $row, $cells);
$cells = $cells[0];
$position = strip_tags($cells[0]);
$plus = strip_tags($cells[1]);
$artist = strip_tags($cells[2]);
$weeks = strip_tags($cells[3]);
echo "\n\t\t" . '{';
echo "\n\t\t\t" . '"position" : "' . $position . '", ';
echo "\n\t\t\t" . '"plus" : "' . $plus . '", ';
echo "\n\t\t\t" . '"artist" : "' . $artist . '", ';
echo "\n\t\t\t" . '"noWeeks" : "' . $weeks . '" ';
echo ($count != (count($rows[0]) - 2)) ? "\n\t\t" . '}, ' : "\n\t\t" . '}';
$count++;
}
}
echo "\n\t" . ']';
echo "\n" . '}';
break;
}?>
The website I'm trying to scrape. The goal is to retrieve json results of the table beginning after LW, TW, Artist, Title, etc. The above returns:
{
"chartDate" : "",
"retrieved" : "1444101246",
"entries" :
[
{
"position" : "7 DayCharts",
"plus" : "Country Past 7 Days -by Overall Rank Return to Main Menu ",
"artist" : " ",
"noWeeks" : "",
"peak" : "",
"points" : "",
"increase" : "",
"us" : ""
},
]
}
instead of
{
"chartDate" : "",
"retrieved" : "1444101246",
"entries" :
[
{
"position" : "2",
"plus" : "1",
"artist" : "KENNY CHESNEY",
"noWeeks" : "Save It For A Rainy"", etc . etc.
},
]
}
What could I add to the code above to retrieve that table?
Update
The problem is the match pattern.
After following statement,
$content = str_replace($newlines, "", html_entity_decode($content));
Some characters are replace or removed, such as " and Some tags are being in UPPERCASE. Hence you are always getting 0 as strpos for $scrape_start no matter what $start_search contains.
So you have to search like,
$start_search ='<TBODY>';
Working code on PhpFiddle