Clean HTML output in ZF2 - html

Is it possible to fomat(clean) output of html in Zend Framework 2? Right now it outputs without proper newline characters and tabs.
I know about this method:
$dom = new DOMDocument();
$dom->preserveWhiteSpace = FALSE;
$dom->loadHTML($html);
$dom->formatOutput = TRUE;
echo $dom->saveHTML();
But I do not understand where I could intercept output in ZF2. Any help would be appreciated.
Right now all the html code is created in layout.

You can attach a listener to the "finish" mvc-event ( http://framework.zend.com/manual/2.1/en/modules/zend.mvc.mvc-event.html ) and have it clean up the response before sending it out.
In your application's module.php add something like the following to the Module class.
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_FINISH, function(MvcEvent $e){
$content = $e->getResponse()->getContent();
$cleancontent = clean_up_html(content); // clean_up_html() not provided
$e->getResponse()->setContent($cleancontent);
});
}

Related

Phoegap/Cordova to load specific DB row after AJAX GET

Im building an app using PHoneGap as the compiler so using HTML5, CSS, JQuery, AJAX etc. Ive manage to get AJAX to GET all the rows from the Database perfectly well, as I have to use .HTML extension on my files I'm struggling to be able to link through to specific DB record. I can do this perfectly in PHP. Im struggling with the HTML part.
Here is my AJAX Loader to get all Rows from DB
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call ...
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MY-URL.COM/videos-mysql.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'POST', //Makes sense only if you passing data
success: function(answer) {
jQuery('#videos-modules').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
error: function() {
//unknown error occorupted
inProcessVideos = false;//Queue is free, guys ;)
}
});
}, 500 );
And here is the contents of the PHP File that renders all the Results from the Database. This part displays the content perfectly.
<?php
include ("../config/mysqli_connect.php");
$sql = ("SELECT * FROM videos");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
<a href='" . $row["id"]. "'>
<div class='video-module'>
<div class='video-thumb'><img src='https://MY-URL.COM/thumbs/" . $row["video_thumb"]. "'></div>
<div class='video-thumb-details'>
<div class='video-thumb-title'> " . $row["id"]. " - " . $row["video_title"]. "</div>
" . $row["publisher_name"]. "
</div>
</div></a>
";
}
} else {
echo "0 results";
}
?>
After the ECHO statement I would normally put something like video-Profile.php?id=$id and it would go to that page and pull in that record from the Database.
However now that I have to do it only in HTML, and im assuming AJAX, how to I achieve this.
Here is the PHP and the MYSQL Query to GET the specific record from the Database. Its currently in MYSQL, I will convert it to MYSQLi once I've got it working and got my head around it.
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "../config/connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM videos WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$video_title = $row["video_title"];
$video_thumb = $row["video_thumb"];
$publisher_name = $row["publisher_name"];
$video_directory = $row["video_directory"];
$video_path = $row["video_path"];
$upload_date = $row["upload_date"];
$video_views = $row["video_views"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo ("$id");?> - <?php echo ("$video_thumb");?>
</body>
</html>
I know this works if I'm running PHP files, and my server is set to PHPv5.3., but before I make it live, it will be sorted to MYSQLi and run on PHP7???
Im looking for inspiration to get this to function via HTML only files.
thanks for your help everyone.
This is a pretty brutalistic way of doing this - typically you'd return JSON or similar from the PHP and then process this into the HTML elements within your JS. But for this case you can do this:
//within call
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id
}) // This allows you to search your child elements and pick them based on criteria
jQuery('#videos-modules').html(contents); // now assign the remaining elements into your html as before
},
I have Tried this but i cant seem to find out how to Run a Console Log as it is Run on iOS iPad at the moment. Can not get it to render in the Browser.
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MYURL.COM/appFiles/tablet/video-profile.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'GET', //Makes sense only if you passing data
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id;
});
jQuery('#videoProfile').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
});
}, 500 );
Struggling with this, i've looked at all the JQuery, AJAX MySQL web sites i can find including W3Schools, Jquery.com and many others. Just can not get it to pass the ID to the PHP file to get the Record from the DB via AJAX.
My Links in the first JQuery AJAX Call are:
<a href='video-Profile.html' data='".$row["id"]."' value='".$row["id"]." '>Some HTML STUFF/Images/Text etc</a>
I can get the ID and the First AJAX Call to show ALL the rows in the DB Table. Now just need to show Record by ID. This is what i cant get my head around. And it must be in .HTML Page as its an App compiled via PhoneGap. I know im repeating my self, Just not to sure if im making my point clear. Thanks for the help in advance.

Yii2: refresh() not working after sending response content

I have a ActiveForm which I use to get some data from and when I click the send button it will run the model (in this case a csv file generator) but the refresh is not working, when I remove the method it will refresh.
After some testing it seems that fputcsv() will stop the script, so that everything that comes after this will not run.
view
public function actionIndex()
{
$model = new Export();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$fields = Yii::$app->request->post('Export');
\backend\models\Export::generate();//this prevents the refresh
Yii::$app->session->setFlash();
return $this->refresh();
} else {
return $this->render('index' , ['model' => $model]);
}
}
model
static public function generate()
{
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="sample.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$data = [array comes here];
$fp = fopen('php://output', 'w') or die("Unable to open file!");
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
foreach ( $data as $line ) {
fputcsv($fp , $line , ';' );
}
stream_get_contents($fp);
fclose($fp);
}
Controller::refresh() uses Location header to reload page. Since headers need to precede the content, you cannot add new header after content was sent. Your Export::generate() method sends content, so you cannot add any header after that, thus $this->refresh() do not work.
Prior to Yii 2.0.14 there was a bug and framework simply ignored that you're trying to send header after content has been send. If you upgrade Yii, you should get "nice" Exception in this case.
If you're trying to display nice page after downloading file, your approach is incorrect. You can't really return file and then redirect to different page. You should first display nice HTML page and inside of it redirect user to download page (for example by using <meta http-equiv="refresh" content="0; url=http://example.com/" /> in head or creating hidden form and submitting it by JavaScript). After downloading the file user will stay at this nice page, so from UX perspective everything should be OK.

Google Translate free api assist

I am kind of new to javascript and building websites, I program c# most of the times.
I am trying to build something and I need to use google translate api, the problem that is cost money so I prefer use Free API so I found this.
https://ctrlq.org/code/19909-google-translate-api
so I changed it a bit and tried alone, because I wasn't sure what e type ment.
so this is my code:
function doGet(text) {
var sourceText = text;
var translatedText = LanguageApp.translate('en', 'iw', sourceText);
var urllog = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ "en" + "&tl=" + "iw" + "&dt=t&q=" + encodeURI(text);
var result = JSON.parse(UrlFetchApp.fetch(urllog).getContentText());
translatedText = result[0][0][0];
console.log(translatedText);
}
so the url is downloading me a text file called "f.txt" that include the translate code the problem is that I doesnt want it to download File,
I just need the translate inside the txt file its gives me,
also the problem is I am not sure how to get that info inside a javascript variable, And I doesnt want it to give me that file as well..
So how Can I read it?
how can I use the file without download it, and How can I push it to a string variable?
And How I can cancel the download and get only the translate?
THANKS!
By the way
and if anyone know the function doGet(e) that I showed on the link, what is "e"? what does the function wants?
I know I'm a year late but I came to same problem and fixed it using PHP. I have created this simple PHP function:
function translate($text, $from, $to) {
if($text == null)
echo "Please enter a text to translate.";
if($from == null)
$from = "auto";
if($to == null)
$to = "en";
$NEW_TEXT = preg_replace('/\s+/', '+', $text);
$API_URL = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" . $from . "&tl=" . $to . "&dt=t&q=" . $NEW_TEXT;
$OUTPUT = get_remote_data($API_URL);
$json = json_decode($OUTPUT, true); // decode the JSON into an associative array
$TRANSLATED_OUTPUT = $json[0][0][0];
echo $TRANSLATED_OUTPUT;
}
Example usage (English to Spanish):
translate("Hello", "en", "es"); //Output: Hola
/*
sourceLanguage: the 2-3 letter language code of the source language (English = "en")
targetLanguage: the 2-3 letter language code of the target language (Hebrew is "iw")
text: the text to translate
callback: the function to call once the request finishes*
* Javascript is much different from C# in that it is an asynchronous language, which
means it works on a system of events, where anything may happen at any time
(which makes sense when dealing with things on the web like sending requests to a
server). Because of this, Javascript allows you to pass entire
functions as parameters to other functions (called callbacks) that trigger when some
time-based event triggers. In this case, as seen below,
we use our callback function when the request to google translate finishes.
*/
const translate = function(sourceLanguage,targetLanguage,text,callback) {
// make a new HTTP request
const request = new XMLHttpRequest();
/*
when the request finishes, call the specified callback function with the
response data
*/
request.onload = function() {
// using JSON.parse to turn response text into a JSON object
callback(JSON.parse(request.responseText));
}
/*
set up HTTP GET request to translate.googleapis.com with the specified language
and translation text parameters
*/
request.open(
"GET",
"https://translate.googleapis.com/translate_a/single?client=gtx&sl=" +
sourceLanguage + "&tl=" + targetLanguage + "&dt=t&q=" + text,
true
);
// send the request
request.send();
}
/*
translate "This shouldn't download anything" from English to Hebrew
(when the request finishes, it will follow request.onload (specified above) and
call the anonymous
function we use below with the request response text)
*/
translate("en","iw","This shouldn't download anything!",function(translation) {
// output google's JSON object with the translation to the console
console.log(translation);
});

How to send parameter with try catch exception in yii2?

I have problem in sending email, looks like our server connection to mail server is unstable, sometimes it successfully sent, but sometimes it's not, it say ssl time out.
So my idea is catch timed out exception and insert in database then I can send later.
But I need to send few parameter with catch exception so I can insert database correctly.
So far what I want is something like this
try{
$message = Yii::$app->mail->compose();
if (Yii::$app->user->isGuest) {
$message->setFrom('from#domain.com');
} else {
$message->setFrom(Yii::$app->user->identity->email);
}
$message->setTo(Yii::$app->params['adminEmail'])
->setFrom(Yii::$app->params['adminEmail'])
->setTo("mymail#gmail.com")
->setSubject('Title 1')
->setHtmlBody("Hi, this is my content to check if registration email successfully sent")
->send();
$mail_from = "no-reply#myweb.com";
$mail_to = "customer#someweb.com";
$content = "here is content of email"
$other = "this other variable";
return 1;
}catch(\Swift_TransportException $e, $mail_from, $mail_to, $content, $other){
//if connection time out or something
$queue = new Queue;
$queue->mail_from = $mail_from;
$queue->mail_to = $mail_to;
$queue->content = $content;
$queue->other = $other;
$queue->fail_reason = $e->getMessage();
$queue->save()
}
but it give me undefined variable $mail_from, $mail_to, and etc
How I can fix my problem?
Thanks in advance.
To fix the undefined variable $mail_from, $mail_to, and etc error it's better to declare the variables outside the try block. Because you're declaring the variables at the end of the try, it fails before these variables are ever initialised.
$mail_from = "no-reply#myweb.com";
$mail_to = "customer#someweb.com";
$content = "here is content of email"
$other = "this other variable";
try {
$message = Yii::$app->mail->compose();
if (Yii::$app->user->isGuest) {
$message->setFrom('from#domain.com');
} else {
$message->setFrom(Yii::$app->user->identity->email);
}
$message->setTo(Yii::$app->params['adminEmail'])
->setFrom(Yii::$app->params['adminEmail'])
->setTo("mymail#gmail.com")
->setSubject('Title 1')
->setHtmlBody("Hi, this is my content to check if registration email successfully sent")
->send();
return 1;
} catch(\Swift_TransportException $e) {
//if connection time out or something
$queue = new Queue;
$queue->mail_from = $mail_from;
$queue->mail_to = $mail_to;
$queue->content = $content;
$queue->other = $other;
$queue->fail_reason = $e->getMessage();
$queue->save()
}
But there are more problems with this code. You're setting the from and to part multiple times. In the if/else you're calling setFrom and then again a few lines later. The same goes for setTo. The last call to the function will overrule the previous set value. So make sure you only call these functions once.

How to Pass a PHP Variable to a MySql Query to Create an Excel Document Download

I am trying to pass a variable from one PHP page to another PHP page, which will trigger an Excel download. However, I cannot figure out how to pass the variable and still have the download trigger. I understand that my PHP page which creates the Excel file cannot have any variables passed to it, or the download will not trigger.
For example, I would like to do the following (very simple example):
variable.php
<?php
$date = '2012-02-15';
echo '<input type="text" id="date" value="'.$date.'"/>';
echo '<span onclick="excelDownload()">Click</span>';
?>
passing.js
function excelDownload(str)
{
Ajax...
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true);
Ajax....
}
excel.php
<?php
Connect to database...
$date = $_GET['date'];
$file = "Names: ";
$result = mysql_query("SELECT * FROM Something WHERE date_field = '$date'");
$data = mysql_fetch_array($result);
$file.= $data['names']." ";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=names.xls");
header("Pragma: no-cache");
header("Expires: 0");
print $file;
?>
Unfortunately, the $_GET[date'] variable causes the excel.php to not download. I have been able to get away with writing static MySql queries within the excel.php page, so I do not have to pass any variables. However, I now have the need to create dynamic excel downloads, but I am not strong enough in php to figure out my options. On a side note, I use Ajax and do not utilize "submit". Will this be a problem?
I figured out my problem and wanted to share my findings to close out this question. Basically, I should have been more detailed in my question. My Ajax function needed some tweaking so that the variable would pass and allow the headers to trigger a download.
I was using the following in my Ajax function:
Ajax...
{
if (xmlhttp.readyState == 4)
{
//nothing to allow download to trigger
}
}
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true):
xmlhttp.send(null);
However, I should have used this:
Ajax...
{
if (xmlhttp.readyState == 4)
{
window.location = "excel.php" + queryString;
}
}
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true):
xmlhttp.send(null);
While I was thinking my problem had to do with output before header(), the real issue was passing the variable.