So I'm trying to use the PHP DOMDocument extension to write a XML document. I have all my code written up, but the only node that appears in the new XML file is the XML header.
Here is the code:
//vars
$history_location="w1/history_files/" . md5($time) . md5(rand(0,1000)) . rand(0,1000) . '.xml';
$id=2;
$airline="Aero Test Ltd.";
$aircraft="Boeing 747-400";
$engine="Rolls-Royce RB211-524H2-T";
$f=5;
$c=25;
$yp=40;
$y=560;
//xml history file
$xml=new DOMDocument();
$xml->formatOutput=true;
//tags
$tag_history=$xml->createElement("history");
$tag_preface=$xml->createElement("preface");
$tag_l1=$xml->createElement("l1", "This is the history file for aircraft " . $id . ".");
$tag_l2=$xml->createElement("l2", "Generated: " . date("F d Y H:i:s", $time) . ".");
$tag_l3=$xml->createElement("l3", "Last Updated: " . date("F d Y H:i:s", $time) . ".");
$tag_body=$xml->createElement("body");
$tag_item=$xml->createElement("item");
$tag_airline=$xml->createElement("airline", $airline);
$tag_aircraft=$xml->createElement("aircraft", $aircraft);
$tag_engine=$xml->createElement("engine", $engine2);
$tag_config=$xml->createElement("config", $f . $c . $yp . $y);
//attr
$attr_name=$xml->createAttribute("name");
$attr_name->value="purchase";
$attr_date=$xml->createAttribute("date");
$attr_date->value=date("F d Y H:i:s", $time);
//sort
$tag_history->appendChild($tag_preface);
$tag_preface->appendChild($tag_l1);
$tag_preface->appendChild($tag_l2);
$tag_preface->appendChild($tag_l3);
$tag_history->appendChild($tag_body);
$tag_body->appendChild($tag_item);
$tag_item->appendChild($attr_name);
$tag_item->appendChild($attr_date);
$tag_item->appendChild($tag_airline);
$tag_item->appendChild($tag_aircraft);
$tag_item->appendChild($tag_engine);
$tag_item->appendChild($tag_config);
//save
$xml->save($history_location);
And all that is saved to the file is <?xml version="1.0"?>.
I've looked through all sorts of documentation, SO questions, and pages of Google searches and have found nothing that explains or solves the problem.
What exactly is going on and what did I screw up to cause the problem?
Thanks in advance,
~Hom
You're missing this before the save() call:
$xml->appendChild($tag_history);
Related
First, I have a few knowledge in PHP, and that is all I could do with my excel export (see attached code below)
It works, but I want to export that excel file with 2 more sheets, I've googled a lot but could not customize the code to insert in it, please, help me if you can
Thank you
<?php
$filename = time().".csv";
header ( 'HTTP/1.1 200 OK' );
header ( 'Date: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Last-Modified: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Content-Type: application/vnd.ms-excel') ;
header ( 'Content-Disposition: attachment;filename='.$filename);
ExportFile1($main_exce);
function ExportFile1($records) {
$do = false;
if(!empty($records)){
foreach($records as $down){
$heading = true;
foreach($down as $row) {
if($heading) {
// display field/column names as a first row
$heading = false;
if(!$do){
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
$do = true;
}
}else{
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
// $d = "\t\n\t\n\t\n";
// print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
}
exit;
?>
The reason you can't make this work is that you are not creating an Excel export here.
You're creating a plain-text, tab-delimited file. Excel can import files in that format, but it's not a true Excel file. It's a simple flat file, and as such, it doesn't support multiple worksheets, unlike a real Excel file.
If you want to solve this, you need to rewrite this code so that it outputs a file which is in the real Excel file format - it's considerably more complex than a tab-delimited text format. There are various libraries available for PHP which can help you easily create real Excel files in xlsx format. Recommendations are off-topic here but they are not hard to find using a search engine.
I'm trying to write a basic error form to a file, but when I submit the file my PHP always crashes. I've tried some basic error fixes such as whether or not the if statement is occurring, if all the variables I'm using are not null, etc...
In my code all the string variables are valid an I am 100% certain they are not causing the error.
I've reduced it down through error testing to be the lines
$destination = fopen($filename,"w");
and
$fclose($destination);
My code:
if(isset($_POST['submit']) && $_POST['name'] != "" && $_POST['email'] != ""){
$filename = "message_" . date('Y-m-d H:i:s') . ".txt";
$issueType = "Type of issue: " . $_POST["issues"] . "\r\n";
$submitter = "Submitted by: " . $_POST["name"];
$email = "Email ID: " . $_POST["email"];
$time = "Submitted at: " . date('Y-m-d H:i:s') . "\r\n";
$message = "Details: " . $_POST["details"];
$destination = fopen($filename,"w");
fwrite($destination,"Issue Alert!");
fwrite($destination,$issueType);
fwrite($destination,$submitter);
fwrite($destination,$email);
fwrite($destination,$time);
fwrite($destination,$message);
$fclose($destination);
}
Any other code I'm implementing is irrelevant as I've cut off those as being points of error.
When I try this with basic, hard-coded strings I don't get any errors. All help is appreciated, Thanks!
Try to change your $filename, as you wrote
$filename = "message_" . date('Y-m-d H:i:s') . ".txt";
because you can't use colon ( ':' from 'H:i:s') in file name.
maybe you can try this:
$filename = "message_" . date('U') . ".txt";
you still have date-time information in your file name
But remember, if you have big traffic on your site, maybe you will get same file name in one second, and the previous existing file will overwrited
This is section of code that I have put in /pgen/admin
<h1><b>List of saved text files:</b></h1>
<?php
$directory = "/pgen/saves/";
$phpfiles = glob($directory . "*.html");
$id = 1;
foreach ($phpfiles as $phpfile) {
$date = " last modified/date created: " . date ("F d Y H:i:s.", filemtime($phpfile));
echo $id.". <a href=$phpfile>".basename($phpfile)."</a>" .$date."<br>";
$id ++;
}
?>
The $directory variable is supposed to be the root of the webpage plus /pgen/saves/.
I have tried using $_SERVER["DOCUMENT_ROOT"]."/pgen/saves".
Also, if I browse using a ftp client, it shows this page is located at /public_html/pgen/admin/ because I am using a 3rd party hosting service.
The code is supposed to list the files in the /pgen/saves folder but the code itself is in the /pgen/admin folder. I've searched everywhere and since I'm new at php, I don't know what to do.
You would be better off to add some error checking/validation to your efforts. When using a foreach() method on an array, you must be aware that it is trusting you to pass it a legit array. If the value passed is not an array, it will try to use it and fail.
$directory = "/pgen/saves/";
$phpfiles = glob($directory . "*.html");
$id = 1;
// Error if no files are found
if (!is_array($phpfiles) && count($phpfiles) <= 0) {
die('no files found');
}
// Otherwise, continue on
foreach ($phpfiles as $phpfile) {
$date = " last modified/date created: " . date ("F d Y H:i:s.", filemtime($phpfile));
echo $id.". <a href=$phpfile>".basename($phpfile)."</a>" .$date."<br>";
$id ++;
}
$sitemap .= " " . '<orders>' . "\n" .
"\t" . '<idKlant>' . $id. '</idKlant>' .
"\n\t" . '<emptyfield></emptyfield>' .
"\n\t" . '<date>' . $verzenddatum . '</date>' . //remaining to get
"\n " . '</orders>' . "\n";
For generating XMl, I am using below code
$xmlobj = new SimpleXMLElement($sitemap);
$xmlobj->asXML("orders.xml");
Output of orders.xml
<orders>
<idKlant>12</idKlant>
<emptyfield/>
<date>30-12-2012</date>
</orders>
What i want is: for Empty xml field there should be Opening and Closing tag as well
<orders>
<idKlant>12</idKlant>
<emptyfield></emptyfield>
<date>30-12-2012</date>
</orders>
Is it possible? OR should i add black space?
As Rolando Isidoro said you can't do it with SimpleXML. But you can always switch to the DOM. Both extension use the same underlying library and representation, so there is very little overhead.
DOMDocument::saveXML can take libxml options as the second parameter and there is LIBXML_NOEMPTYTAG which does exactly what you want.
e.g.
<?php
$o = new SimpleXMLELement(data());
$docRoot = dom_import_simplexml($o);
echo $docRoot->ownerDocument->savexml($docRoot,LIBXML_NOEMPTYTAG);
function data() {
return '<orders>
<idKlant>12</idKlant>
<emptyfield/>
<date>30-12-2012</date>
</orders>';
}
prints
<orders>
<idKlant>12</idKlant>
<emptyfield></emptyfield>
<date>30-12-2012</date>
</orders>
I'm experiencing a very strange problem with my PHP script "hanging" even after the background processes have finished running. I am running PHP 5.3, Windows Server 2008 R2, IIS7 with Tomcat Apache installed.
Project Background My script generates PDF forms through the "shell_exec()" function. Anywhere between 1 - 3,000 forms can be generated. Once all forms have been generated, a download link and "start over" link are supposed to show at the bottom of the page -- instead, the site continues to "load" and the links never show up -- even when I check the server and see that all files have finished generating.
This issue only comes up when generating 300+ forms, which takes 3-6mins.
I have set my php.ini's "max_execution_time" to 1200 (20mins), and IIS7's "Connection Timeout" is also set to 1200 seconds. Here are links to pictures of these settings to confirm I have them set properly:
http://i49.tinypic.com/15gavew.png -- php.ini
http://i49.tinypic.com/9u5j0n.png -- IIS7
Is there another setting that I am missing? Is there a Tomcat Apache Connection Timeout setting that I am unaware of? Does PHP have another "timeout" setting besides "max_execution_time" and "set_time_out"? I've exhausted my resources and have not a clue as to why my script continues to hang, even after the "while loop" has finished running and all PDFs have been successfully created.
Thank you for any and all help/advice.
While Loop Code
/* build zip & directory for PDFs */
$zip = new ZipArchive;
$time = microtime(true);
$new_dir = "c:/pdfgenerator/f-$time";
if(!file_exists($new_dir)) {
mkdir($new_dir);
}
$res = $zip->open("pdf/tmppdf/mf-pdfs_" . $time . ".zip", ZipArchive::CREATE);
$num = 0;
while($row = mysql_fetch_array($result)) {
/* associate a random # assigned to each PDF file name */
$num++;
include($form);
$rand = rand(1,50000);
$file_num = $num * $rand;
$fo = fopen('c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.html', 'w') or die("can't open file");
fwrite($fo, $output);
echo shell_exec('c:\wkhtmltopdf\wkhtmltoimage c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.html c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg');
/* the follow uses ghost script to execute the ImageMagick convert command from cmd.exe */
$magick_dir = 'C:\imagemagick'; // install IM in short DOS 8.3 compatible path
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg -resize "1710x2200^!" c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg' ;
echo shell_exec($send_cmd);
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.pdf';
echo shell_exec($send_cmd);
/* EO ghostscript code */
/* add the newly generated files to the Zip Archive */
if ($res === TRUE) {
//echo "RESULT TRUE...";
$zip->addFile('c:/pdfgenerator/f-' . $time . '/mf_pdf-' . $time . '-' . $file_num . '.pdf','c:/pdfgenerator/f-' . $time . '/mf_pdf-' . $time . '-' . $file_num . '.pdf');
//echo "FILE ADDED!";
}
}
echo "<h2>Download Zip</h2>";
echo "<h2>Start Over</h2>";
$zip->close("pdf/tmppdf/mf-pdfs_" . $time . ".zip", ZipArchive::close());
}
}
Specific Shell Lines
echo shell_exec('c:\wkhtmltopdf\wkhtmltoimage c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.html c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg');
/* the follow uses ghost script to execute the ImageMagick convert command from cmd.exe */
$magick_dir = 'C:\imagemagick'; // install IM in short DOS 8.3 compatible path
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg -resize "1710x2200^!" c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg' ;
echo shell_exec($send_cmd);
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.pdf';
echo shell_exec($send_cmd);
converted all of my mysql_ functions, which are now deprecaded as of PHP 5.5, and utilized MySQLi functions.