xml generation from php if file doesnt exist - php

This code works if file is previously expisting but if file doesn't exist this code doesnt work.
$doc = new DOMDocument();
$doc->version = '1.0';
$doc->encoding = 'ISO-8859-1';
$response = $doc->createElement('response');
$doc->appendChild($response);
$response_type= $doc->createElement('response_type','Yes');
$response_id = $doc->createElement('response_id',$max_id_site);
$response->appendChild($response_type);
$response->appendChild($response_id);
$doc->formatOutput = true;
echo $doc->saveXML();
$doc->save('$filename_xml');
updated code
$doc = new DOMDocument();
$doc->version = '1.0';
$doc->encoding = 'ISO-8859-1';
$response = $doc->createElement('response');
$doc->appendChild($response);
$response_type= $doc->createElement('response_type','Yes');
$response_id = $doc->createElement('response_id',$max_id_site);
$response->appendChild($response_type);
$response->appendChild($response_id);
$doc->formatOutput = true;
echo $doc->saveXML();
if (! is_file($filename_xml)) {
touch($filename_xml) or trigger_error("Can't Create File");
$doc->save($filename_xml);
}

You can replace
$doc->save('$filename_xml');
with
if (! is_file($filename_xml)) {
touch($filename_xml) or trigger_error("Can't Create File");
$doc->save($filename_xml);
}

Use file_exists() to check if file is already there.
Replace last line:
$doc->save('$filename_xml');
with
if( file_exists( $filename_xml ) == false ) {
$doc->save( $filename_xml );
}
In general you should not even generate the xml if file is there.
BTW: Putting $filename_xml) in "`" is wrong.

Related

php, how to clone DOMElement?

Official documentation says that DOMElement has inherited method cloneNode http://php.net/manual/en/class.domelement.php . If i try to clone, it does not work. How to copy element from one DOMDocument to another? Namely, i have misplaced head, thus i have somehow to copy head and body, and than to echo them in right order.
ob_start();
$viewData = $this->data;
include_once( $this->viewTemplPath.$this->file );
$buffer = ob_get_clean();
$doc = new \DOMDocument();
$doc->loadHTML($buffer);
$head = $doc->getElementsByTagName('head')->item(0);
print_r('<br><br> 184 view.php head='); var_dump($head);
$body = $doc->getElementsByTagName('body')->item(0);
print_r('<br><br> 188 view.php body='); var_dump($body);
$docNew = new \DOMDocument();
$headNew = $head->cloneNone(true); // Fatal error: Call to undefined method DOMElement::cloneNone()
$docNew->appendChild($headNew);
$bodyNew = $body->cloneNone(true); // Fatal error: Call to undefined method DOMElement::cloneNone()
$docNew->appendChild($bodyNew);
echo $docNew->saveHTML();
In order to clone the Element, the solution is to import the Element i want to clone to the Document, and than add it as a child : http://php.net/manual/en/domdocument.importnode.php
This does not through errors, and echoes the new document.
But this does not resolve the problem with misplaced head.
ob_start();
$viewData = $this->data;
include_once( $this->viewTemplPath.$this->file );
$buffer = ob_get_clean();
$doc = new \DOMDocument();
$doc->loadHTML($buffer);
$head = $doc->getElementsByTagName('head')->item(0);
$body = $doc->getElementsByTagName('body')->item(0);
$docNew = new \DOMDocument();
$headNew = $docNew->importNode($head, true);
$docNew->appendChild($headNew);
$bodyNew = $docNew->importNode($body, true);
$docNew->appendChild($bodyNew);
echo $docNew->saveHTML();
You have typo mistake,
you wrote it CloneNone(true),
it should be cloneNode(true)

CSV: Undefined Offset -> Convert to XML

I have this CSV file: http://www.gamesdeal.com/media/feedgenerator/Gamekey.csv
And get this error with PHP:
PHP Notice: Undefined offset: 6 in
But the problem is that I can not create the CSV file by my self. It is from a store. So, I can't modify it... Does somebody knows how I can fix this error?
Here my code:
function csvToXML($inputFilename, $outputFilename, $delimiter = ','){
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile, 0, $delimiter);
// Create a new dom document with pretty formatting
$doc = new DOMDocument('1.0', 'utf-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('products');
$root = $doc->appendChild($root);
while (($row = fgetcsv($inputFile, 0, $delimiter)) !== false) {
$container = $doc->createElement('product');
foreach ($headers as $i => $header) {
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, 'w');
fwrite($handle, $strxml);
fclose($handle);
}
Here is the problem:
header: products_price <tab> price_currency
data: 5.45 EUR (no tab between 5.45 and EUR)
So in the header there are 7 fields defined, but only 6 in the data (also most records don't have a EAN value, but there's a tab at the end, so that should be ok).
To fix this you could:
read all the fields manually
first replace products_price <tab> price_currency with products_price price_currency in the header
remove price_currency from $headers
or somehow let the parser know there are only 6 fields instead of 7
You probably have to correct the price field afterwards then.

xml generated not opening in browser

I wrote php code to create an xml but the xml file is not opening in browser
The following is the code:
$dom = new DOMDocument('1.0','UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement('journal');
$dom->appendChild($root);
$journal_metadata = $dom->createElement('journal_metadata');
$dom->appendChild($journal_metadata);
$journal_metadata->appendChild($dom->createElement('full_title', 'Economics'));
$journal_metadata->appendChild($dom->createElement('abbrev_title', 'JJD'));
$issn = $dom->createElement('issn','2142');
$journal_metadata->appendChild($issn);
$issn->setAttribute('media_type', 'electronic');
$journal_metadata->appendChild($dom->createElement('doi_data', 'JJD'));
$doi_data = $dom->createElement('doi_data');
$journal_metadata->appendChild($doi_data);
$doi = $dom->createElement('doi', '10.E');
$doi_data->appendChild($doi);
$resource = $dom->createElement('resource', 'http://localhost/fo/journal.php?jid=1');
$doi_data->appendChild($resource);
// journal issue
$journal_issue = $dom->createElement('journal_issue');
$dom->appendChild($journal_issue);
// journal article
$journal_article = $dom->createElement('journal_article');
$dom->appendChild($journal_article);
$journal_article->setAttribute('publication_type', 'full_text');
$pages = $dom->createElement('pages');
$journal_article->appendChild($pages);
$resource = $dom->createElement('resource', htmlspecialchars('http://localhost/fo/abstracts.php?artID=472&jid=1'));
$doi_data->appendChild($resource);
echo '<xmp>'. $dom->saveXML() .'</xmp>';
$dom->save('result.xml') or die('XML Create Error');

Reading xlsx file in PHP

I'm following this tutorial to read the xlsx file format. I'm reading xlsx file. Working fine. But it display all the file content in one line. How to add space between them? Thanks
Here is my code.
$file_upload = 'book.zip';
$zip = new ZipArchive;
// the string variable that will hold the file content
$file_content = " ";
// the uploaded file
//$file_upload = $file -> upload["tmp_name"];
if ($zip -> open($file_upload) === true) {
// loop through all slide#.xml files
if ( ($index = $zip -> locateName("xl/sharedStrings.xml")) !== false ) {
$data = $zip -> getFromIndex($index);
$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
$file_content = strip_tags($xml -> saveXML());
}
echo $file_content;
}
Solved. Just add this line.
$xml->formatOutput = true; Full code here.
$file_upload = 'book.zip';
$zip = new ZipArchive;
// the string variable that will hold the file content
$file_content = " ";
// the uploaded file
//$file_upload = $file -> upload["tmp_name"];
if ($zip -> open($file_upload) === true) {
// loop through all slide#.xml files
if ( ($index = $zip -> locateName("xl/sharedStrings.xml")) !== false ) {
$data = $zip -> getFromIndex($index);
$xml->formatOutput = true;
$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
$file_content = strip_tags($xml -> saveXML());
}
echo $file_content;
Try this? Tested on PHP 5.5.3
$file_upload = 'book.zip';
$zip = new ZipArchive;
$dom = new DOMDocument;
// the string variable that will hold the file content
$file_content = " ";
// the uploaded file
//$file_upload = $file -> upload["tmp_name"];
if ($zip->open($file_upload) === true) {
// loop through all slide#.xml files
$index = $zip->locateName("xl/sharedStrings.xml");
if ($index !== false) {
$data = $zip->getFromIndex($index);
$dom->loadXML(
$data,
LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING
);
$dom->formatOutput = true;
$file_content = strip_tags($dom->saveXML());
}
}
echo $file_content;

PHP Script to convert .CSV files to .XML

Just wondering if anyone can point me in the direction of some tips / a script that will help me create an XML from an original CSV File, using PHP.
Cheers
This is quite easy to do, just look at fgetcsv to read csv files and then DomDocument to write an xml file. This version uses the headers from the file as the keys of the xml document.
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$inputFilename = 'input.csv';
$outputFilename = 'output.xml';
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('rows');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('row');
foreach($headers as $i => $header)
{
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
The code given above creates an XML document, but does not store it on any physical device. So replace echo $doc->saveXML(); with
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
There are a number of sites out there that will do it for you.
If this is going to be a regular process rather than a one-time thing it may be ideal to just parse the CSV and output the XML yourself:
$csv = file("path/to/csv.csv");
foreach($csv as $line)
{
$data = explode(",", $line);
echo "<xmltag>".$data[0]."</xmltag>";
//etc...
}
Look up PHP's file and string functions.
Sorry to bring up an old thread but I tried this script and I'm getting a DOM Exception error
The headers of our CSV Files are display_name office_number mobile_number and the error I'm receiving is DOMDocument->createElement('\xEF\xBB\xBFdisplay_name') #1 {main}

Categories