PHP - Create multiple XML files from Mysql data - php

I'm pulling data from my mysql database and using it to create an XML file. the idea is for each row of data pulled, it be appended to its own XML file
Here's my sample code:
//sql statement here
$results = $fetch_data->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $data)
{
$invoice_no = $data["invoice_no"];
$doc = new DOMDocument();
$doc->formatOutput = true;
$Order = $doc->appendChild($doc->createElement('Order'));
$OrderHead = $Order->appendChild($doc->createElement('OrderHead'));
$Schema = $doc->createElement('Schema');
$Schema->appendChild($doc->createElement('Version', '3.05'));
$OrderHead->appendChild($Schema);
$CrossReference = $doc->createElement('CrossReference', $invoice_no);
$OrderHead->appendChild($CrossReference);
//more xml code...
$doc->save($invoice_no.".xml", LIBXML_NOEMPTYTAG);
}
As shown above, i'm looping through the data from the database to create the XML file then want to save each file(s) prefixed by the $invoice_no. But only one XML file is created and to be more specific, only the last record pulled from the database is used to create the XML file. this is happening though i'm creating the file inside my loop
where could i be going wrong?

Related

How to get specific values on an xml using php?

I'm creating a simple web app using html and php, this app reads an XML file provided by a user on a webpage and then prints some values content on it.
The files are sent to the server by POST and then are read by a php script.
This is a fragment of my xml test file:
<cfdi:Impuestos totalImpuestosTrasladados="72.07">
<cfdi:Traslados>
<cfdi:Traslado importe="50.00" impuesto="IEPS" tasa="16.00"/>
<cfdi:Traslado importe="22.07" impuesto="IVA" tasa="16.00"/>
</cfdi:Traslados>
</cfdi:Impuestos>
And this is my code made on php:
<?php
foreach ($_FILES['archivos']['name'] as $f => $name) {
$tempPath = $_FILES["archivos"]["tmp_name"][$f];
//Load xml file directly on the temp path
$xml = simplexml_load_file($tempPath, null, true);
$namespaces = $xml->getDocNamespaces();
//Creating and loading DOM object
$dom = new DOMDocument('1.0','utf-8');
$dom->load($tempPath);
//Getting IVAs' values
foreach ($xml->xpath('//cfdi:Comprobante//cfdi:Impuestos//cfdi:Traslados//cfdi:Traslado') as $impuestos){
$IVA = $impuestos['importe'];
echo("IVA = ".$IVA."<br>");
}
}
?>
That prints:
IVA = 50.00
IVA = 22.07
Print's screenshot
On this case I want to print only the IVA's value but it takes the IEPS' value too because IEPS is on the same path as IVA. These values are only on this part of the file and I don't know if there's a way to separate them.
I just want to select only the IVA's value. Would you help me please?:(
The complete XML file is: Here
Try:
foreach ($xml->xpath("//cfdi:Comprobante//cfdi:Impuestos//cfdi:Traslados//cfdi:Traslado[#impuesto='IVA']") as $impuestos){

How to update excel data into existing XML file using PHP

I want to add excel file data into an existing XML file and a particular tag.
I want to add excel data of upc code into the upc tag of the XML file using PHP.
My excel file format is:
I want the following XML format data.
$xml = simplexml_load_file("yourxmlfilename.xml");
$prod = $xml->Products;
print_r($prod->Product->count());
for($i=1; $i<=$prod->Product->count();$i++){
$str = (string) $prod->Product[$i]->ExternalId;
if($str == 'mobilesn1'){
$c = $prod->Product[$i]->UPCs;
print_r($prod->Product[$i]->UPCs->UPC);
if((string)$prod->Product[$i]->UPCs->UPC !="895623" ){
//unset($prod->Product[$i]->UPCs->UPC);
$c->addChild('UPC', '895623');
$xml->asXML("yourxmlfilename.xml");
}
}
}

PHP DOMDocument messing up encoding

I'm using class to load html on one page, get HTML table content. The page is in windows-1250, so I'm using iconv to convert it to utf-8.
All this is done in one class, that I'm calling like this: $tableHtml = suplUpdater::getTableHtml(someParams,...);. When I echo that variable directly, everything looks nice. However, I want to parse the table rows with PHP DOMDocument to save them to database. Code looks like this:
$tableData = suplUpdater::getTableHtml(1400450400);
//echo($tableData);
$document = new DOMDocument();
$document->loadHTML($tableData);
$rows = $document->getElementsByTagName('tr');
$rows->item(0)->parentNode->removeChild($rows->item(0));//first row is just a header
$output = array();
foreach ($rows as $row) {
$currentOutput = array();
foreach ($row->childNodes as $cell) {
if ($cell->nodeType == 1) {
$currentOutput[] = $cell->nodeValue;
}
}
$output[] = $currentOutput;
}
When I do var_dump($output);, I get array, but it has messed up encoding. Where could be the problem? If needed, I can provide source table data.
EDIT:
When I copy table html to txt file, encoded in utf-8 and I do file_get_contents('tableHtml.txt'), I get the same result.
EDIT:
I have uploaded sample data here:http://anagmate.moxo.cz/data.txt
EDIT:
Screenshot of echo and var_dump is here:http://anagmate.moxo.cz/supl.png

XMLWriter using with loop in php

i want to create multiple XML file by using php. i used following code which is working fine for single XML file generation but when i try to same code in loop for generation multiple XML file with different name its throw an error but file is save in destination driver can anyone help me to solve this issue
$fileName = date('YmdHis').rand('0000','999999')."output.xml";
working fine for single calling
xmlGenerater($pimcoArr ,$fileName);
error throw when i call it in loop
for($=0;$i<2;$i++){
xmlGenerater($pimcoArr ,$fileName);
}
error message screen
XML file genartion method
function xmlGenerater($data ,$fileName){
if(!empty($data)){
$writer = new XMLWriter();
//lets store our XML into the memory so we can output it later
$writer->openMemory();
//lets also set the indent so its a very clean and formatted XML
$writer->setIndent(true);
//now we need to define our Indent string,which is basically how many blank spaces we want to have for the indent
$writer->setIndentString(" ");
//Lets start our document,setting the version of the XML and also the encoding we gonna use
//XMLWriter->startDocument($string version, $string encoding);
$writer->startDocument("1.0", "UTF-8");
//lets start our main element,lets call it “ersvpresponse”
$writer->startElement('ersvpresponse');
$loop = 1;
foreach($data as $dataRow){
$pimco_id = $dataRow['pimco_id'];
$event_id = $dataRow['event_id'];
$contact_id = $dataRow['contact_id'];
$status = $dataRow['status'];
$writer->startElement("contact");
if($loop==1){
$dateTime = date('Y-m-d');
$writer->writeAttribute("updated",$dateTime);
}
//now we create pimcoeventid node
$writer->startElement("pimcoeventid");
$writer->text("$pimco_id");
$writer->endElement();
//now we create pimcocontactid node
$writer->startElement("pimcocontactid");
$writer->text("$contact_id");
$writer->endElement();
//now we create pimcocontactid node
$writer->startElement("ersvpstatus");
$writer->text("$status");
$writer->endElement();
$writer->endElement();
$loop++;
}
//Now lets close our main element
$writer->endElement();
//close our document
$writer->endDocument();
/*Lets output what we have so far,first we need to set a header so we can display the XML in the
browser,otherwise you will need to look at the source output. */
header('Content-type: text/xml');
//lets then echo our XML;
//echo $writer->outputMemory();
/* that is enough to display our dynamic XML in the browser,now if you wanna create a XML file we need to do this */
$filename = "exportFiles/$fileName";
//lets output the memory to our file variable,and we gonna put that variable inside the file we gonna create
$file = $writer->outputMemory();
//lets create our file
file_put_contents($filename,$file);
}
}
You are putting the documents in separate files on the server but you send them to the client as one single repsonse document, hence the
Line Number 14
<?xml ...
and that doesn't work, you can't just concatenate xml documents and expect the client-side parser to accept that.
But you could e.g. zip those files and send the archive.

Create XML via PHP & MySQL (for use by action script 2) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse HTML with PHP?
Get MySQL database output via PHP to XML
I have some tables in MySQL.... Can I use PHP to create a .xml file on my website that will neatly contain the information from my MySQL database?
On a side note if I am retrieving xml information in action script 2.0 do I HAVE to retrieve it from a .xml file or can I have a .php file that creates an open and close tag on the page and then creates an xml table on the .php page?
you can create XML in PHP and you can save it as file or echo as XML string , you can use below sample codes
$xml = new DOMDocument('1.0', 'iso-8859-1');
$rootNode = $xml->createElement('xmlrootnode');
$rootNode = $xml->appendChild($rootNode);
foreach( $resultArr as $r ) {
$sDateArr = explode( ' ', $r['start_time'] );
$sRootN = $xml->createElement('date');
$sRootN = $rootNode->appendChild($sRootN);
$sRootN->setAttribute('value', $sDateArr[0]);
//Id field
$idN = $xml->createElement('id');
$idN = $sRootN->appendChild($idN);
$idT = $xml->createTextNode(htmlentities($r['id']));
$idN->appendChild($idT);
}
//$xml->save($xml);
//header('Content-type: text/xml');
//echo $xmlStr = $xml->saveXML();
$xmlStr = isset($xml) ? htmlspecialchars($xml->saveXML()) : '';
As an answer to your side note:
Yes you can - thats the normal way to do it.
AS does not even know if it was a file or created on the fly - it just receives the data and if it is valid XML it should work...

Categories