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");
}
}
}
Related
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){
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?
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.
Hello I have the following xml results that are returned from a remote site
<ResultSet totalResultsAvailable="1">
<Product orderNo="5321" partNo="A2345" truckable="1">
<Manufacturer id="22">WIDGET 4 U</Manufacturer>
<Model id="356">ACME 500</Model>
<Years>95-98</Years>
<ProductType id="23" categoryID="4">Cool Red Widgest</ProductType>
<Material id="6">shiny stuff</Material>
<PartNo>A2345</PartNo>
<Code/>
</Product>
</ResultSet>
I am simply trying to pull the xml results and place in a new csv file with the following code:
but I get and error: Warning:
Invalid argument supplied for foreach() in /home/myServer/public_html/xmlParser2.php on line 14
Here is my code:
<?
echo 'Write XML to CSV';
$basenameLong ='http://thisIsTheURLto.com/myFeed/?key=123456789&mode=getProducts;
$fileNameCSV = 'xmlParseContent.csv';
$feedContent = '';
echo '<br/>Starting......';
$feedContent = file_get_contents($basenameLong);
$fh = fopen($fileNameCSV, 'w+'); //create new CSV file if not exists else append
foreach($feedContent->ResultSet->Product as $product) {
fputcsv($f, get_object_vars($product),',','"');
}
fclose($fh);
?>
I know this code is very elementary but can you help me find the issue. I am a novice and I dont see it.
This line is wrong :
fputcsv($f, get_object_vars($product),',','"');
if you want to put blank values, try doing this :
fputcsv($f, get_object_vars($product),'','','');
Your problem is that you never parse your XML file. Replace file_get_contents with simplexml_load_file and it should work.
Using PHP to convert XML to CSV is fairly easy, at least in the situations I've encountered so far. In my case, it would save me significant work if I could simply convert structured XML data into CSV data. Typically, I want to convert only the data in a particular xpath of the original XML document. The PHP function below will load an XML file and convert the elements in the specified xpath to simple csv data.
function xml2csv ($xmlFile, $xPath) {
// Load the XML file
$xml = simplexml_load_file($xmlFile);
// Jump to the specified xpath
$path = $xml->xpath($xPath);
// Loop through the specified xpath
foreach($path as $item) {
// Loop through the elements in this xpath
foreach($item as $key => $value) {
$csvData .= '"' . trim($value) . '"' . ',';
}
// Trim off the extra comma
$csvData = trim($csvData, ',');
// Add an LF
$csvData .= "\n";
}
// Return the CSV data
return $csvData;
}
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...