Description:
I have the follwoing code:
if(isset($riskTriggerFlag) && $riskTriggerFlag==1) // if risk_mitigator process reads and offer weight is maintained based on offer mentioned.
{
echo "Risk Weight: ".$risk_weight ."\n";
$randNo = rand(1,100);
echo "Random Weight: ". $randNo ."\n";
if($randNo < intval(100 - $risk_weight))
{
$flagThrowPostback = 1;
}
}
As you can see,I am putting \n in the text,but still the message in getting printed in this matter:
Risk Weight: 20 Random Weight: 20
What am I doing wrong?
Note:
I can't use br tag or nl2br() since the total page is just a php page, and I don't want to add any html tags.
output on broswer is coming like this:
<html>
<head></head>
<body>Multiple row Risk Weight: 20 Random Weight: 20 </body>
</html>
I think better way is to check whether php file is executed from CLI or browser. In case it is from browser then use else newline.
$newline = "<br />";
if (PHP_SAPI === 'cli')
{
// ...
$newline = "\n";
}
if(isset($riskTriggerFlag) && $riskTriggerFlag==1) // if risk_mitigator process reads and offer weight is maintained based on offer mentioned.
{
echo "Risk Weight: ".$risk_weight . $newline;
$randNo = rand(1,100);
echo "Random Weight: ". $randNo . $newline;
if($randNo < intval(100 - $risk_weight))
{
$flagThrowPostback = 1;
}
}
Related
Has anyone found a solution, how to display a message in the browser every second using PHP?
Until now, I've always used the following code, which worked fine on my server running IIS 6:
<html>
<body>
<?php
for ($counter = 0; $counter <= 10; $counter++) {
echo "Message after " . $counter . " second(s)<br>";
ob_flush();
flush();
sleep(1);
}
?>
</body>
</html>
I've seen several posts that ob_flush no longer works with the newer IIS versions.
I use IIS on Windows 10.
In some posts I read to add responseBufferLimit="0" into the section PHP_via_FastCGI of the file C:\Windows\System32\inetsrv\config\applicationHost.config.
But in this file I've only the following section about fastCgi so I've no idea how to add responseBufferLimit="0" into this section:
<fastCgi>
<application fullPath="C:\Program Files\PHP\php-cgi.exe" />
</fastCgi>
Any help is very appreciated.
I've done some tests. It's still a workaround, but a bit smarter and I think as long as there's no better solution, you can live with it.
You just have to add echo str_repeat(" ", 7500000); at the very beginning of your code and ob_flush() and flush() will do what they're supposed to do (also with the new IIS versions):
<html>
<body>
<?php
echo str_repeat(" ", 7500000);
for ($counter = 0; $counter <= 10; $counter++) {
echo "Message after " . $counter . " second(s)<br>";
ob_flush();
flush();
sleep(1);
}
?>
</body>
</html>
The following code is definitely not a smart and good solution, but maybe you can use it as a workaround until someone here shows us the smart solution, which I'm also very interested in.
<html>
<body>
<?php
for ($counter = 0; $counter <= 10; $counter++) {
echo "Message after " . $counter . " second(s)";
echo str_repeat(" ", 10000000) . "<br>";
sleep(1);
}
?>
</body>
</html>
I have the following PHP code: When it is commented out (as it is now) from just after the comment // ... more stuff in here to the end of that comment block, my page renders html from that 2nd php block as expected as in this screenshot.
If I uncomment that block it renders like the screenshot after the code below which is not what I want (I want the rendered html as in the first screenshot). The only thing not showing in my comment block is a function call that curls a webpage, parses html with DomXNode types of things, and returns an array with 3 elements. How can I get the original rendering of the html back and what am I possibly doing that is ruining that for me? I tried echo instead of print and that makes no difference.
I honestly did search for the answer on here and found lots of pages describing how do do just the opposite of what I want so please be gentle with me. I was surprised that I couldn't find a similar question and I know there has to be an easy answer here. Thanks!
<?php
// ... more stuff in here
/*
include("../../includes/curl_fx.php");
if ($doAppend === "parcel") {
$lines = explode(PHP_EOL, $Data);
foreach($lines as $line) {
if(strpos($line, "http") > 0) {
$start = stripos(strval($line), "http");
$fullLength = strlen($line);
$urlLength = ($fullLength - $start);
$fullUrl = substr($line, $start, $urlLength);
$arraySDAT = getSDAT($fullUrl);
$line .= ", " . $arraySDAT[0] . ", " . $arraySDAT[1] . ", " . $arraySDAT[2] . "\n";
fwrite($Handle, $line);
}
}
}
*/
?>
<?php
if ($DataAdded === true) {
print "<h2>YourFile.txt</h2>Data has been added.<br />Close this window or tab to return to the web map.<br />";
} else {
print "Data may not have been added. Check the file.<br />";
}
fclose($Handle);
print $doAppendAnswer;
print "<br />";
?>
EDIT: Here is the function.
<?php
function getSDAT ($fullUrl="") {
$ch = curl_init($fullUrl);
if (! $ch) {
die( "Cannot allocate a new PHP-CURL handle" );
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
header("Content-type: text");
curl_close($ch);
libxml_use_internal_errors(true);
libxml_clear_errors();
$doc = DOMDocument::loadHTML($data);
$xpath = new DOMXPath($doc);
$ownName1query = '//table/tr/td/span[#id="MainContent_MainContent_cphMainContentArea_ucSearchType_wzrdRealPropertySearch_ucDetailsSearch_dlstDetaisSearch_lblOwnerName_0"][#class="text"]';
$ownName2query = '//table/tr/td/span[#id="MainContent_MainContent_cphMainContentArea_ucSearchType_wzrdRealPropertySearch_ucDetailsSearch_dlstDetaisSearch_lblOwnerName2_0"][#class="text"]';
$ownAddrquery = '//table/tr/td/span[#id="MainContent_MainContent_cphMainContentArea_ucSearchType_wzrdRealPropertySearch_ucDetailsSearch_dlstDetaisSearch_lblMailingAddress_0"][#class="text"]';
$entries = $xpath->query($ownName1query);
foreach($entries as $entry) {
$ownname1 = $entry->nodeValue;
}
$entries = $xpath->query($ownName2query);
foreach($entries as $entry) {
$ownname2 = $entry->nodeValue;
}
$entries = $xpath->query($ownAddrquery);
$pattern = '#<br\s*/?>#i';
$replacement = ", ";
$i=0;
foreach($entries as $entry) {
$ownAddr = $entry->nodeValue;
if(!$entry->childNodes == 0) {
$ownAddr = $doc->saveHTML($entry);
}
$ownAddr2 = preg_replace($pattern, $replacement, $ownAddr, 15, $count); // replace <br/> with a comma
$ownAddr3 = strip_tags($ownAddr2);
}
return array($ownname1, $ownname2, $ownAddr3);
}
Your problem is:
header("Content-type: text");
Just remove that. Why is it there?
As mentioned, it's the header which is causing you a problem. You see the header decides the type of content that the current document should have or how the current document should behave - an information that is usually found in the < head >...< /head > part of an HTML. You can use it for declaring the content type, controlling the cache, redirecting, and etc.
When you use header("Content-type: text"), you are deciding that the content of the current document "yourdocument.php" would be a text instead of the default which is HTML.
header("Content-type: text/html");
echo "<html>This would make mypage.php behave as an HTML</html>";
// This is usually unnecessary since text/html is already the default header
header("Content-type: text/javascript");
echo "this would make mypage.php behave as a javascript";
header("Content-type: text/css");
echo "this would make mypage.php behave as a CSS";
header('Content-type: image/jpeg');
readfile("source/to/my/file.jpg");
// this would make mypage.php display file.jpg and act as a jpg
header('Content-type: image/png');
readfile("source/to/my/file.png");
// this would make mypage.php display file.png and act as a png
header('Content-type: image/gif');
readfile("source/to/my/file.gif");
// this would make mypage.php display file.gif and act as a gif
header('Content-type: image/x-icon');
readfile("source/to/my/file.ico");
// this would make mypage.php display file.ico and act as an icon
header('Content-type: image/x-win-bitmap');
readfile("source/to/my/file.cur");
// this would make mypage.php display file.cur and act as a cursor
I've been given data from a previous version of a website (it was a custom CMS) and am looking to get it into a state that I can import it into my Wordpress site.
This is what I'm working on - http://www.teamworksdesign.com/clients/ciw/datatest/index.php. If you scroll down to row 187 the data starts to fail (there should be a red message) with the following error message:
Fatal error: Uncaught exception 'Exception' with message 'String could
not be parsed as XML' in
/home/teamwork/public_html/clients/ciw/datatest/index.php:132 Stack
trace: #0
/home/teamwork/public_html/clients/ciw/datatest/index.php(132):
SimpleXMLElement->__construct('
Can anyone see what the problem is and how to fix it?
This is how I'm outputting the date:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
ini_set('memory_limit','1024M');
ini_set('max_execution_time', 500); //300 seconds = 5 minutes
echo "<br />memory_limit: " . ini_get('memory_limit') . "<br /><br />";
echo "<br />max_execution_time: " . ini_get('max_execution_time') . "<br /><br />";
libxml_use_internal_errors(true);
$z = new XMLReader;
$z->open('dbo_Content.xml');
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
// move to the first <product /> node
while ($z->read() && $z->name !== 'dbo_Content');
$c = 0;
// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'dbo_Content')
{
if($c < 201) {
// either one should work
$node = simplexml_import_dom($doc->importNode($z->expand(), true));
if($node->ClassId == 'policydocument') {
$c++;
echo "<h1>Row: $c</h1>";
echo "<pre>";
echo htmlentities($node->XML) . "<br /><br /><br /><b>*******</b><br /><br /><br />";
echo "</pre>";
try{
$xmlObject = new SimpleXMLElement($node->XML);
foreach ($xmlObject->fields[0]->field as $field) {
switch((string) $field['name']) {
case 'parentId':
echo "<b>PARENT ID: </b> " . $field->value . "<br />";
break;
case 'title':
echo "<b>TITLE: </b> " . $field->value . "<br />";
break;
case 'summary':
echo "<b>SUMMARY: </b> " . $field->value . "<br />";
break;
case 'body':
echo "<b>BODY:</b> " . $field->value . "<br />";
break;
case 'published':
echo "<b>PUBLISHED:</b> " . $field->value . "<br />";
break;
}
}
echo '<br /><h2 style="color:green;">Success on node: '.$node->ContentId.'</h2><hr /><br />';
} catch (Exception $e){
echo '<h2 style="color:red;">Failed on node: '.$node->ContentId.'</h2>';
}
}
// go to next <product />
$z->next('dbo_Content');
}
} ?>
</body>
</html>
The error message you're getting "String could not be parsed as XML" means that the XML parser found something in the input data that was not valid XML.
You haven't shown us the data, so I can't tell you exactly what is invalid, but something in there is failing to meet the strict rules for XML parsing. There are any number of possible reasons for this.
If I had to stick my neck out on the line and guess, I'd say the most common reason cause of bad XML in the middle of a file that is otherwise okay would be an unescaped & when it should be the & entity code.
Anyone creating their XML using a proper XML writer shouldn't have this issue, but I've come across plenty of cases where people don't bother using an XML writer and just output raw XML as text and have forgotten to escape the entities, which means that that the data is fine until you come to a company name with an & in it.
If it's as simple as that, and it's a one-off import, you may be able to fix the file manually in a text editor.
However that's just a guess. You'll need to actually examine the XML file for yourself to see the problem. If you can't see the problem visually, I'd suggest using a GUI XML tool to analyse the file.
Hope that helps.
[EDIT]
Okay, I just took a better look at the data in the link you gave, and on thing sticks out like a sore thumb....
encoding="utf-16"
I note that all the data that has worked was using UTF-8, and all the data that has failed is using UTF-16.
PHP is generally fine with UTF-8, but it won't cope very well at all with UTF-16. So it's fairly clear that this is your problem.
And, to be honest, there's really no need to ever use UTF-16, so the solution here is to switch to UTF-8 encoding for everything.
How easy that is for you to do, I can't say, but worst case I'm sure you could find a batch convertion tool.
Hope that helps.
I am using PHP and want to run 2 functions, one after the other.
These functions are getallmydata() and createCSV()
The code below runs the first function fine but the second function createCSV() is not working. It seems like it is not being called properly.
Is there anything wrong with the structure of my code as both functions work correctly independently? I cannot work this out!
<?php
//run this function//
getallmydata();
//then run this function//
createCSV();
function getallmydata(){
require_once dirname(__FILE__).'/cm/csrest_general.php';
require_once dirname(__FILE__).'/cm/csrest_clients.php';
require_once dirname(__FILE__).'/cm/csrest_campaigns.php';
$api_key = 'MY API KEY';
$wrap = new CS_REST_General($api_key);
$result = $wrap->get_clients();
$Content = "";
if ($result->was_successful()) {
foreach ($result->response as $client) {
$client_wrapper = new CS_REST_Clients($client->ClientID, $api_key);
$client_details_result = $client_wrapper->get();
$campaigns_result = $client_wrapper->get_campaigns();
if ($client_details_result->was_successful()) {
/* This is where the client details will be */
$client_details = $client_details_result->response;
echo ('<pre>');
/*print out the company name*/
echo "Company Name = " . $client_details->BasicDetails->CompanyName . "<br/>";
/*print out the company markup*/
echo "Markup On Delivery = " . $client_details->BillingDetails->MarkupOnDelivery . "<br/>";
$count = 0;
if ($campaigns_result->was_successful()) {
/*print out the latest campaign name of the current campaign*/
foreach ($campaigns_result->response as $campaign_ob) {
echo 'Latest Campaign Name = ' . $campaign_ob->Name . '<br/>';
//echo 'Latest Subject = ' . $campaign_ob->Subject . '<br/>';
//echo 'Total Recipients = ' . $campaign_ob->TotalRecipients . '<br/>';
//echo 'Sent Date = ' . $campaign_ob->SentDate . '<br/>';
/*Set content for CSV File*/
//$Content .= "This is within the loop \n";
$count++;
if($count > 0) break;
}/*end loop*/
}/*end campaigns if statement*/
echo ('</pre>');
} else {
echo 'Failed with code '.$client_details_result->http_status_code."\n<br /><pre>";
var_dump($client_details_result->response);
}
}
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo ('</pre>');
}
} //end main function
/*create the downloadable csv file*/
function createCSV(){
$FileName = date("d-m-y") . '.csv';
# Titlte of the CSV
//$Content = "Company_Name Markup Campaign_Name Subject Recipients Date \n";
# fill data in the CSV
//$Content .= "\"John Doe\",\"New York, USA\",15,65465464 \n";
$Content .= "Testing The Function Works OK \n";
//$Content .= "This should be another line";
header('Content-Type: application/csv');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}//end csv download function
/*end create downloadable .csv file */
?>
I think you should get the error: headers already sent. (you checked that the second function is called right? You can find it out by placing a echo on the first line of the function.)
You are trying to create a CSV page but you are parsing HTML in the first function, so the header is already sent to the client saying that it is a normal HTML page. Remove these echo's in the first function and it should work.
Quote of the PHP manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
More info about headers: PHP header
First think I would tell you is
1 you should first write function definition and then you should call a function
i.e
function getallmydata(){
// function code
}
function createCSV(){
// function code
}
getallmydata();
createCSV();
2 . The second thing is that check that is there any white space left in the code out side php code or any o/p that is sent as resonse as because when ever you user header() at that if any kind of content other than header() is sent as response then header() function fails. Try this things and check again.
My entire PHP page only displays as text and no PHP code is executed. It's weird because when I test it using <? phpinfo(); ?> in a test.php file, I get a successful test and it works on my Apache server. However when I attempt to do anything else. It only shows as text.
Edit: Here is the link to the code. I couldn't figure out how to post it here. Pastebin
<?php
// create short variable names
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$find = $_POST['find'];
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
echo "<p>Order processed at ".date('H:i, jS F Y')."</p>";
echo "<p>Your order is as follows: </p>";
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo "Items ordered: ".$totalqty."<br />";
if ($totalqty == 0) {
echo "You did not order anything on the previous page!<br />";
} else {
if ($tireqty > 0) {
echo $tireqty." tires<br />";
}
if ($oilqty > 0) {
echo $oilqty." bottles of oil<br />";
}
if ($sparkqty > 0) {
echo $sparkqty." spark plugs<br />";
}
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
echo "Subtotal: $".number_format($totalamount,2)."<br />";
$taxrate = 0.10; // local sales tax is 10%
$totalamount = $totalamount * (1 + $taxrate);
echo "Total including tax: $".number_format($totalamount,2)."<br />";
if($find == "a") {
echo "<p>Regular customer.</p>";
} elseif($find == "b") {
echo "<p>Customer referred by TV advert.</p>";
} elseif($find == "c") {
echo "<p>Customer referred by phone directory.</p>";
} elseif($find == "d") {
echo "<p>Customer referred by word of mouth.</p>";
} else {
echo "<p>We do not know how this customer found us.</p>";
}
?>
</body>
</html>
I am willing to bet 10$ that test.php uses <?php, and the changed code uses <?, while the server does not understand it as an opening tag since short_open_tags is off in php.ini.
A lot of books use <? for open tags, while most servers only support the long version (<?php). If that's the case, then changing all the simple <? to <?php will do the trick.
PHP code is only exposed in 1 case: When PHP interpreter does not identify it as PHP code. That can be caused by only 2 problems:
Wrong configuration of Apache (or other http server) which doesn't handle php files at all.
Wrong open tags in PHP files, so PHP doesn't know when code begins.
If the file is a *.php, if Apache is turned on serving *.php files through PHP interpreter, if standard open tags are used or PHP is configured to use other types of used tags, and if you're accessing this PHP file through the browser, in no circumstances would PHP expose this code.