Downloaded json file has extra slashes - php

I have found a way to download my json file that contains some json content in wordpress, on form submit, by calling on an external file download.php that will then execute header(). This works, however the json file that I get by downloading has escaped all characters. Even double quotes. And the json I echo out before downloading, doesn't.
Downloaded .json:
{\"post\":[{\"ID\":3467,\"post_author\":
Echoed out .json:
{"post":[{"ID":3467,"post_author":"1"
I've added the menu page:
add_menu_page( 'Download JSON', 'Download JSON', 'manage_options', 'custompage', 'download_json', 'dashicons-download', 6000 );
In my download_json() function, I have
$json_out = json_encode($output);
$download = htmlspecialchars($json_out);
echo '<form method="post" action="'.plugins_url().'/my_plugin/download.php">
<input type="hidden" name="json" value="'.$download.'">
<button type="submit" class="button-secondary">Download JSON</button>
</form>';
$output is my array with stuff in it. The json in the hidden input field looks like the echoed out one. In my download.php file I have
<?php
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="content.json"');
$json_contents = $_POST['json'];
echo $json_contents;
This downloads the content.json file when I click on the button, but I have extra escaped characters, and I'm not sure why.
Any help is appreciated.

Here is my old function I used on PHP4 to remove slashes, but only if they were automatically added.
Please note that usage of magic_quotes is highly discouraged. (I don't think it even exists in PHP5, not sure)
This function can take an plain value, or an array, and will do it on all elements then. I haven't used it in years, so be sure to test if it does what you want.
function stripslashesIfAutoAdded($something){
// This function removes added slashes
// It only removes them if they were added.
$mq_on = get_magic_quotes_gpc();
if (is_array($something)){
// loop over it and remove slashes where needed
$retArr = array();
foreach($something as $oneElement) {
if ($mq_on){
$retArr[] = stripslashes($oneElement);
} else {
$retArr[] = $oneElement;
}
}
return $retArr;
} else {
if ($mq_on){
return stripslashes($something);
} else {
return $something;
}
}
}

Related

How can I replace braces with <?php ?> in php file?

I wanna replace braces with <?php ?> in a file with php extension.
I have a class as a library and in this class I have three function like these:
function replace_left_delimeter($buffer)
{
return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}
function replace_right_delimeter($buffer)
{
return(str_replace("}", "; ?> ", $buffer));
}
function parser($view,$data)
{
ob_start(array($this,"replace_left_delimeter"));
include APP_DIR.DS.'view'.DS.$view.'.php';
ob_end_flush();
}
and I have a view file with php extension like this:
{tmp} tmpstr
in output I save just tmpstr and in source code in browser I get
<?php echo $tmp; ?>
tmpstr
In include file <? shown as <!--? and be comment. Why?
What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.
You will need to instead preprocess the PHP source file before evaluating it, e.g.
$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);
However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.
do this:
function parser($view,$data)
{
$data=array("data"=>$data);
$template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$replace = array();
foreach ($data as $key => $value) {
#if $data is array...
$replace = array_merge(
$replace,array("{".$key."}"=>$value)
);
}
$template=strtr($template,$replace);
echo $template;
}
and ignore other two functions.
How does this work:
process.php:
<?php
$contents = file_get_contents('php://stdin');
$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;
bash script:
process.php < my_file.php
Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.
Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.

Converting text to UTF-8 within PHP script

I am exporting data to CSV from a dynamic html table.
However this causes some problems because sometimes the data has control characters etc.
I need all these stripped out or made 'friendly' if possible?
I have no idea how to do this so could anyone help?
Here is my script:
<textarea name="siteurl" rows="10" cols="50">
<?php //Check if the form has already been submitted and if this is the case, display the submitted content. If not, display 'http://'.
echo (isset($_GET['siteurl']))?htmlspecialchars($_GET['siteurl']):"http://";?>
</textarea><br>
<input type="submit" value="Submit">
</form>
</div>
<div id="nofloat"></div>
<table class="metadata" id="metatable_1">
<?php
error_reporting(E_ALL);
//ini_set( "display_errors", 0);
function parseUrl($url){
//Trim whitespace of the url to ensure proper checking.
$url = trim($url);
//Check if a protocol is specified at the beginning of the url. If it's not, prepend 'http://'.
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
//Check if '/' is present at the end of the url. If not, append '/'.
if (substr($url, -1)!=="/"){
$url .= "/";
}
//Return the processed url.
return $url;
}
//If the form was submitted
if(isset($_GET['siteurl'])){
//Put every new line as a new entry in the array
$urls = explode("\n",trim($_GET["siteurl"]));
//Iterate through urls
foreach ($urls as $url) {
//Parse the url to add 'http://' at the beginning or '/' at the end if not already there, to avoid errors with the get_meta_tags function
$url = parseUrl($url);
//Get the meta data for each url
$tags = get_meta_tags($url);
//Check to see if the description tag was present and adjust output accordingly
$tags = NULL;
$tags = get_meta_tags($url);
if($tags)
echo "<tr><td>Description($url)</td><td>" .$tags['description']. "</td></tr>";
else
echo "<tr><td>Description($url)</td><td>No Meta Description</td></tr>";
}
}
?>
</table>
<script type="text/javascript">
var exportTable1=new ExportHTMLTable('metatable_1');
</script>
<div>
<input type="button" onclick="exportTable1.exportToCSV()" value="Export to CSV"/>
<input type="button" onclick="exportTable1.exportToXML()" value="Export to XML"/>
</div>
</body>
I'm guessing you want something like:
echo "<tr><td>Description($url)</td><td>" . utf8_encode($tags['description']) . "</td></tr>";
Please specify what text is it that is displaying wrong, is it $tags['description']?
Here are the manuals for function you probably need: mb_convert_encoding, utf8_encode.
Not sure if I understand the question correctly, but if all you want is an UTF-8 encoded CSV, you could just use utf8_encode() on the data you're writing to the file.
Alternatively, if you want to omit control chars, you could check the lines for controle chars before writing them to the file using ctype_cntrl()... and then, using either a regular expression to get rid of them, or refuse to write the lines all together.

Posting form data to PHP script and then Posting results back again

The below script fetches meta data on a list of URL's.
The URL's are inputted on my front end, I managed to get the data to another page (this script) but now instead of echo'ing the table onto the same page the script is on I want to feed that data back to my front end and put it in a nice table for the user to see.
How would I make the php script echo the data on another page?
thanks
Ricky
<?php
ini_set('display_errors', 0);
ini_set( 'default_charset', 'UTF-8' );
error_reporting(E_ALL);
//ini_set( "display_errors", 0);
function parseUrl($url){
//Trim whitespace of the url to ensure proper checking.
$url = trim($url);
//Check if a protocol is specified at the beginning of the url. If it's not, prepend 'http://'.
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
//Check if '/' is present at the end of the url. If not, append '/'.
if (substr($url, -1)!=="/"){
$url .= "/";
}
//Return the processed url.
return $url;
}
//If the form was submitted
if(isset($_POST['siteurl'])){
//Put every new line as a new entry in the array
$urls = explode("\n",trim($_POST["siteurl"]));
//Iterate through urls
foreach ($urls as $url) {
//Parse the url to add 'http://' at the beginning or '/' at the end if not already there, to avoid errors with the get_meta_tags function
$url = parseUrl($url);
//Get the meta data for each url
$tags = get_meta_tags($url);
//Check to see if the description tag was present and adjust output accordingly
$tags = NULL;
$tags = get_meta_tags($url);
if($tags)
echo "<tr><td>$url</td><td>" .$tags['description']. "</td></tr>";
else
echo "<tr><td>$url</td><td>No Meta Description</td></tr>";
}
}
?>
I think its best to use Ajax for this right? So it doesn't refresh
i prefer the ajax method as its much cleaner..
Whats important is the $.ajax(); and the echo json_encode()
Documentation
php manual for json_encode() - http://php.net/manual/en/function.json-encode.php
jquery manual for $.ajax(); - http://api.jquery.com/jQuery.ajax/
List of Response Codes - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Example Code
Without seeing your HTML i'm guessing here.. but this should get you started in the right path for using ajax.
form html
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="siteUrl" id="siteUrl">
<input type="submit" name="submit" value="submit" class="form-submit">
</form>
example-container
In your case, this is a table, just set the table ID to example-container
ajax
This requires you to use the jquery library.. If you use another library in additon called data tables, you can streamline a lot of this jquery appending of <tr>'s
// On the click of the form-submit button.
$('.form-submit').click(function(){
$.ajax({
// What data type do we expect back?
dataType: "json",
// What do we do when we get data back
success: function(d){
alert(d);
// inject it back into a table called example-container
// go through all of the items in d and append
// them to the table.
for (var i = d.length - 1; i >= 0; i--) {
$('#example-container').append("<tr><td>"+d[i].url+"</td><td>"+d[i].description+"</td></tr>");
};
},
// What do we do when we get an error back
error: function(d){
// This will show an alert for each error message that exist
// in the $message array further down.
for (var i = d.length - 1; i >= 0; i--) {
alert(d[i].url+": "+d[i].message);
};
}
});
// make sure to have this, otherwise you'll refresh the page.
return false;
});
modified php function
<?php
//If the form was submitted
if(isset($_POST['siteurl'])){
//Put every new line as a new entry in the array
$urls = explode("\n",trim($_POST["siteurl"]));
//Iterate through urls
foreach ($urls as $url) {
//Parse the url to add 'http://' at the beginning or '/' at the end if not already there, to avoid errors with the get_meta_tags function
$url = parseUrl($url);
//Get the meta data for each url
$tags[] = get_meta_tags($url);
}
if($tags):
echo json_encode($tags);
else:
$message[] = array(
'url' => $url,
'message' => 'No Meta Description'
);
// This sets the header code to 400
// This is what tells ajax that there was an error
// See my link for a full ref of the codes avail
http_response_code(400);
echo json_encode($message);
endif;
}
You would have to either:
1 - submit to the frontend page, including this PHP code on that page instead.
2 - Use AJAX to post the form, get the output and put it somewhere on the frontend page.
Personally, I'd use the first method. It's easier to implement.

Using json_encode to send html returns “null” string at the end

I'm using this to load php functions and send them to javascript in a plugin, like:
function me_nav_query_submit() {
$urlcall = nav_me_paises(); /* fetches a large html string */
$response = json_encode($urlcall); /* encode to display using jQuery */
//header( "Content-Type: application/json" );
echo $response;
exit;
}
I insert the html on the page, using
function(response) {
jQuery('#navcontainer').html(response);
}
and everything works fine, except that i get a "null" string at the very end of the result.
json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn't seem to be the case. I've also tried using utf8_encode() with no success. I've read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append "null" to the end.
note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a "headers already sent" error.
Any ideas?
EDIT this is the function called:
function nav_me_paises() {
?>
<ul class="navcategorias">
<?php $tquery = $_POST['wasClicked']; ?>
<?php $navligas = get_terms($tquery,'hide_empty=0') ?>
<?php foreach ($navligas as $liga) : ?>
<?php $link = get_term_link($liga); ?>
<li class="liga"><a href="<?php echo $link; ?>" ><?php echo $liga->name; ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
nav_me_paises() is not returning anything. the html block is treated as output!
function nav_me_paises() {
$output = '<ul class="navcategorias">';
$tquery = $_POST['wasClicked'];
$navligas = get_terms($tquery,'hide_empty=0')
foreach ($navligas as $liga) {
$link = get_term_link($liga);
$output .= '<li class="liga"><a href="'.$link.'" >'.$liga->name.'</a></li>';
}
$output .='</ul>';
return $output;
}
nav_me_paises() doesn't return anything. Passing this "nothing" to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it
function foo()
{
};
var_dump(json_encode(foo()));
string(4) "null"
Also, if it's just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.
I presume all you wanna do is put that HTML inside some div, because you'd not parse it into a DOM and process its elements... because if u'd do that u'd not use HTML for it.

javascript return function's data as a file

I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.

Categories