I have a php loop, but it keeps printing the value next to each other instead of clearing the first loop value and replacing it with the new loop value. Here is my code.
while (1==1) {
$a=array("red","green","blue","yellow","brown");
$x=array_rand($a,3);
sleep(5);
print $a[$x[0]];
}
Basically it just needs to echo out a new random value on its own every 5 seconds, currently it doesn't remove the old value.
Try use jquery, the below example is for random numbers.
<script>
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()*6);
//Do whatever you want with that number
$('#holder').html(rand);
}
</script>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>Random Number</title>
</head>
<body>
<div id='holder'></div>
</body>
</html>
For random text
var names = ['test1', 'test2', 'test3', 'test4'];
setInterval(function() {
var rand = Math.floor(Math.random() * 4);
document.getElementById("name").innerHTML = names[rand];
}, 2000);
<div id="name">test</div>
I am not sure if i understand what you are trying to accomplish, but I think this is what you are trying to do.
$a=array("red","green","blue","yellow","brown");
while (count($a)) {
$x=array_rand($a);
sleep(5);
echo chr(13). $a[$x];
}
Related
I'm currently using DOM Parser for my project. Also, I'm using CURL in php to scraping the website. I want to get a value from the script tag in the head of the HTML I get. But I really confused how to do that. If run the code bellow :
$data_dom = new simple_html_dom();
$data_dom->load($html);
foreach($data_dom->find('script') as $script){
echo $script->plaintext."<br>";
}
The result was the empty value, when I inspect it, only br tag appear. I want to get everything that using script tag. Here is the head value :
<head>
I will give you the script I want to get
.....
<script type="text/javascript">
var keysearch = {"departureLabel":"Surabaya (SUB : Juanda) Jawa Timur Indonesia","arrivalLabel":"Palangkaraya (PKY : Tjilik Riwut | Panarung) Kalimantan Tengah Indonesia","adultNum":"1","childNum":"0","infantNum":"0","departure":"SUB","arrival":"PKY","departDate":"20181115","roundTrip":0,"cabinType":-1,"departureCode":"ID-Surabaya-SUB","arrivalCode":"ID-Palangkaraya-PKY"};
(function(window, _gtm, keysearch){
if (window.gtmInstance){
var departureExp = keysearch.departureCode.split("-");
var arrivalExp = keysearch.arrivalCode.split("-");
gtmInstance.setFlightData({
'ITEM_TYPE': 'flight',
'FLY_OUTB_CODE': departureExp[2],
'FLY_OUTB_CITY': departureExp[1],
'FLY_OUTB_COUNTRYCODE': departureExp[0],
'FLY_OUTB_DATE': keysearch.departDate,
'FLY_INB_CODE': arrivalExp[2],
'FLY_INB_CITY': arrivalExp[1],
'FLY_INB_COUNTRYCODE': arrivalExp[0],
'FLY_INB_DATE': keysearch.returnDate,
'FLY_NBPAX_ADL': keysearch.adultNum,
'FLY_NBPAX_CHL': keysearch.childNum,
'FLY_NBPAX_INF': keysearch.infantNum,
});
gtmInstance.pushFlightSearchEvent();
}
}(window, gtmInstance, keysearch));
var key = "rkey=10fe7b6fd1f7fa1ef0f4fa538f917811dbc7f4628a791ba69962f2ed305fb72d061b67737afd843aaaeeee946f1442bb";
var staticRoot = 'http://sta.nusatrip.net';
$(function() {
$("#currencySelector").nusaCurrencyOptions({
selected: getCookie("curCode"),
});
});
</script>
</head>
I want to get the key variable. I will use it to get the data from the website. Thanks
Depending on what the rest of the markup looks like, you may be able to just use DOMDocument and XPath, then parse out the value of the var with preg_match. This example will echo the key.
<?php
$html = <<<END
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var keysearch = {"departureLabel":"Surabaya (SUB : Juanda) Jawa Timur Indonesia","arrivalLabel":"Palangkaraya (PKY : Tjilik Riwut | Panarung) Kalimantan Tengah Indonesia","adultNum":"1","childNum":"0","infantNum":"0","departure":"SUB","arrival":"PKY","departDate":"20181115","roundTrip":0,"cabinType":-1,"departureCode":"ID-Surabaya-SUB","arrivalCode":"ID-Palangkaraya-PKY"};
(function(window, _gtm, keysearch){
if (window.gtmInstance){
var departureExp = keysearch.departureCode.split("-");
var arrivalExp = keysearch.arrivalCode.split("-");
gtmInstance.setFlightData({
'ITEM_TYPE': 'flight',
'FLY_OUTB_CODE': departureExp[2],
'FLY_OUTB_CITY': departureExp[1],
'FLY_OUTB_COUNTRYCODE': departureExp[0],
'FLY_OUTB_DATE': keysearch.departDate,
'FLY_INB_CODE': arrivalExp[2],
'FLY_INB_CITY': arrivalExp[1],
'FLY_INB_COUNTRYCODE': arrivalExp[0],
'FLY_INB_DATE': keysearch.returnDate,
'FLY_NBPAX_ADL': keysearch.adultNum,
'FLY_NBPAX_CHL': keysearch.childNum,
'FLY_NBPAX_INF': keysearch.infantNum,
});
gtmInstance.pushFlightSearchEvent();
}
}(window, gtmInstance, keysearch));
var key = "rkey=10fe7b6fd1f7fa1ef0f4fa538f917811dbc7f4628a791ba69962f2ed305fb72d061b67737afd843aaaeeee946f1442bb";
var staticRoot = 'http://sta.nusatrip.net';
$(function() {
$("#currencySelector").nusaCurrencyOptions({
selected: getCookie("curCode"),
});
});
</script>
</head>
<body>foo</body>
</html>
END;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query('//script');
foreach($result as $currScriptTag)
{
$currScriptContent = $currScriptTag->nodeValue;
$matchFound = preg_match('/var key = "(.*)"/', $currScriptContent, $matches);
if($matchFound)
{
/*
* $matches[0] will contain the whole line like var key = "..."
* $matches[1] just contains the value of the var
*/
$key = $matches[1];
echo $key.PHP_EOL;
}
}
I experience the following problem. By clicking the button in start.php the file fakten02.php is called with the parameter DE2 . This parameter is used as a variable variable to convert the array $DE2 into a string and display it in start.php. Unfortunately, this does not happen. If fakten02.php is directly called with the parameter, it works. If the parameter is hard-coded in fakten02.php the content of $land is shown in start.php. However, if $land is filled from $text2, $land is empty in start.php.
start.php
<!DOCTYPE HTML>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="spalten">
<button type="submit" id="land1">Klicken</button>
</div>
<?php
include("fakten02.php");
print_r($land);
?>
</body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#spalten > button").click(function() {
$.get("fakten02.php", {sland:'DE2'});
<?php echo $land; ?>;
})
})
</script>
</html>
fakten02.php
<?php
$parameter = $_GET['sland'];
//$parameter=$_REQUEST['sland'];
//print_r($_REQUEST);
$DE2 = array("ich", "bin", "groß");
//echo "Text $text";
//$text2 = "$".$parameter;
$param2 = $parameter;
$text2 =$$param2;
for ($i=0; $i < count($text2); $i++) {
$land.="$text2[$i] "; //Does not work
$land.= "daten[$i] = '$DE2[$i]';"; //Returns expected data
}
//print( "aus 2 $land, $param2");
?>
I don't understand this behaviour. I did a lot of searching here and on Google, but I could not find a similar problem. How can I resolve this issue?
This is my code. It should display the alert box if the reset date stored in a textfile is equal to the current date and the data from the tables(mysql) are not zero.. Then it should reset the values to zero and delete other records. I've tried echoing the if statement and it's 1.Not sure why the alert box is not popping up..
<?php
function reset1(){
$sql=mysql_query("UPDATE tbl_txbookStock SET suppliedQuantity=0, boughtQuantity=0");
$sql=mysql_query("DELETE FROM tbl_order");
$sql=mysql_query("DELETE FROM tbl_order_book");
//overwrite date
$myFile = "config/config.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$resetDate = fread($fh, filesize($myFile));
fwrite($fh,date("m/d/Y",strtotime("+1 years")));
fclose($fh);
}
function getCurrentDate(){
return date('m/d/Y');
}
function resetDateIsToday($resetDate){
$itIs=false;
if($resetDate==getCurrentDate())
$itIs=true;
return $itIs;
}
function isReset(){
$isReset=false;
if(countZeroQuantities()==countBooks()){
$isReset=true;
}
return $isReset;
}
function countBooks(){
$sql=mysql_query("select count(bookID) as count from tbl_textbook");
$row=mysql_fetch_array($sql);
return $row['count'];
}
function countZeroQuantities(){
$sql=mysql_query("select count(bookID) as count FROM `tbl_txbookStock` where suppliedQuantity>0 OR boughtQuantity>0");
$row=mysql_fetch_array($sql);
return $row['count'];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>TEXTBOOK ORDERING SYSTEM</title>
<link rel="stylesheet" href="templatemo_style.css">
<?php if (!isset($_SESSION['loggedin'])){ {?>
<?php if(resetDateIsToday(getResetDate())&&!isReset()){?>
<script type="text/javascript">
<!--
function confirmReset(){
var answer = confirm ("Reset is scheduled today.Do you really want to reset?")
if (answer===1){
<?php reset1();?>
window.location="index.php";
}else{
alert('Records not reset...');
window.location="index.php";
}}
// -->
</script>
<? }}}?>
</head>
<body>
</body>
</html>
I dont see where you execute confirmReset , maybe just write
window.onload =function(e){
confirmReset();
}
at the end of your script
confirm() returns true/false, and "true === 1" is not true.
just write your confirm control like this,
var answer = confirm ("Reset is scheduled today.Do you really want to reset?")
if (answer){
...
}
Ok, what I am trying to do is make a javascript loop of images, but first I have to get a list of the images. In javascript there is no way to directly grab this text file... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt but it can be done eaisly in php, I am currently gettung the txt file using php, but the javascript cannot read the variable. How can I make javascript be able to read this variable. Here is what I have...
<?php
$file = "http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"; //Path to your *.txt file
$contents = file($file);
$string = implode($contents);
echo $string;
?>
<script type="text/javascript">
function prnt() {
var whatever = "<?= $string ?>";
alert(whatever);
}
</script>
You can use echo or print to write to the page in PHP.
var whatever = "<?php echo $string; ?>";
Although, if the file has line breaks in it, you will need to remove those.
Make it a bit more interesting: go ahead and split the fields and use JSON encoding. It should read directly in javascript without needing to call JSON.parse() on the client.
<?php
$lines = file_get_contents('http://...');
$lines = explode("\n",trim($lines));
foreach ($lines as &$line) {
$line = preg_split('/,? /',$line);
}
$js = json_encode($lines);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var dar = <?php echo $js; ?>;
</script>
</body>
</html>
You should also consider using a local proxy to cache the results of that file if you plan to run this frequently and especially if you are going to serve it up on a public web server somewhere. Store the file locally as "noaa_data.txt" and have a second script on a cron job (12 hours or something):
<?php
file_put_contents("/var/www/noaa_data.txt",file_get_contents("http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"));
?>
Hi i am trying to retrieve data from mysql database to create flot graph
can anyone walk me through this procedure or give me an idea of what to do
thanks
You probably want something like this. I haven't used flot but I looked at the example here.
<?php
//create array of pairs of x and y values
$dataset1 = array();
while ($row = mysql_fetch_assoc()) { //or whatever
$dataset1[] = array( $row['xvalue'], $row['yvalue'] );
}
?>
<script type="text/javascript">
//put array into javascript variable
var dataset1 = <?php echo json_encode($dataset1); ?>;
//plot
$(function () {
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
Adding upon the example from #Tom Haigh:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Flot Examples</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$server = "localhost";
$user="user";
$password="password";
$database = "some_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
query = "SELECT x_axis_values, y_axis_values FROM some_table";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['x_axis_value'],$row['y_axis_value']);
}
?>
<script type="text/javascript">
$(function () {
var dataset1 = <?php echo json_encode($dataset1); ?>;
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
</body>
</html>
as #Tom Haigh say work well, but you need to add another code to work well, I was using the example, but I discover in the source code it add to the result quotes " so to avoid this just add the: intval to the array, example:
<?php
$query = "SELECT valx, valy FROM chart";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$d2[] = array (intval($row['valx']),intval($row['valy']));
}
?>
This depends largely on your environment and requirements. There's lots of free tools out there you can use. One example is Flot that lets you use jQuery to build graphs. There's link to documentation on the Google Code page.