inserting data into mysql database through xml - php

while i am inserting data into database using normal xml tree structure data is successfully inserted but while i am trying to insert data into database using different xml structure it is not gives me any error but at the same time fields are created but i can't visualize content in table to,
<?xml version="1.0"?>
<xml>
<draw>
<candelete>yes</candelete>
<forpayroll>no</forpayroll>
<name>hello</name>
</draw>
</xml>
above xml format which successfully insert data into mysql database
below xml format is not allowing me to insert data into mysql database
<ENVELOPE>
<HEADER>
<VERSION>1</VERSION>
<STATUS>1</STATUS>
</HEADER>
<BODY>
<DESC>
</DESC>
<DATA>
<TALLYMESSAGE>
<LEDGER NAME="Dena" RESERVEDNAME="" ID="2240" REQNAME="dena">
<PARENT TYPE="String">Bank Accounts</PARENT>
<TAXTYPE TYPE="String">Others</TAXTYPE>
<ISBILLWISEON TYPE="Logical">No</ISBILLWISEON>
<ISCOSTCENTRESON TYPE="Logical">No</ISCOSTCENTRESON>
<ISREVENUE TYPE="Logical">No</ISREVENUE>
<ISDEEMEDPOSITIVE TYPE="Logical">Yes</ISDEEMEDPOSITIVE>
<CANDELETE TYPE="Logical">Yes</CANDELETE>
<FORPAYROLL TYPE="Logical">No</FORPAYROLL>
<MASTERID TYPE="Number"> 2240</MASTERID>
<TNETBALANCE TYPE="Amount">0.00</TNETBALANCE>
<LANGUAGENAME.LIST>
<NAME.LIST TYPE="String">
<NAME>Dena</NAME>
</NAME.LIST>
<LANGUAGEID TYPE="Number">0</LANGUAGEID>
</LANGUAGENAME.LIST>
</LEDGER>
</TALLYMESSAGE>
</DATA>
</BODY>
</ENVELOPE>
below is my php insert connection code
<?php
$con = mysql_connect("localhost:3306","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("temp", $con);
if(!$xml=simplexml_load_file('./xml/data.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
foreach ($xml as $syn)
{
$candelete = $syn->candelete;
$forpayroll = $syn->forpayroll;
$name = $syn->name;
$sql = "INSERT INTO vtiger (candelete, forpayroll, name) VALUES ('$candelete','$forpayroll','$name')";
$query = mysql_query($sql);
if (!$query)
{
echo ('Error: ' . mysql_error());
}
else
{
echo "Record added";
}
}
mysql_close($con);
?>

I'd like you to look at your foreach loop to read xml:
foreach ($xml as $syn)
{
$candelete = $syn->candelete;
$forpayroll = $syn->forpayroll;
$name = $syn->name;
as you see here you decleare xml nodes wich are totally different in new xml, so you need to parse your document and get all relevant data to build the query. A good approch would be to loop among <TALLYMESSAGE> to retrieve all relevant data and store into variables wich you will be able to use for the new query.
You can use simplexml_load_file to do that.
Documentation: here
NOTE You query also must be changed according with new xml, you will need a new table with a correct schema.
UPDATED
You can still use the same way to parse file but you need to change your script and you will end up with more lines of code to parse the entire new xml. As you can see structure is totally different hand have many child nodes wich cannot be retrieved by using a simple foreach as you did for the first file wich didn't have any child nodes. That's why you really should use simplexml_load_file, less work

You need to think more about your foreach loop, bcause in your working xml file thats only one array so you can retrieve data using only one foreach loop, but your another xml file i think it contains more array so you need to create one or more foreach loop according to its structure.

you define your conection to mysql in $con
you must also use mysql_query($sql, $con);

Related

php simplexml adding children-nodes in a loop

I'm having a trouble with SimpleXML and addChild().
I am trying to generate an order-file in XML from data in a mysql database.
I want the file to be formed like so:
<Ordreimport>
<Kunde>
<..>
<Orderline>
<data>
</orderline>
<orderline>
<data>
</orderline>
</kunde>
</ordreimport>
The problem is that the following code
$OrderXML = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-1"?><OrdreImport></OrdreImport>');
While ($kunderad = mysql_fetch_array($HentKunde)) {
$OrderXML->addChild('Kunde');
$KundeInfo = $OrderXML->Kunde->addChild('KundeID',''); //BD60 - Kundekort - Kundenr
$OrdreHode = $OrderXML->Kunde->addChild('OrdreHode'); //OF14 - Ordrehode
$OrdreHode= $OrderXML->Kunde->OrdreHode->addChild('OrdreLinje');
while ($olrader = mysql_fetch_array($HentOrdrelinje)) {
$OrdreLinje = $OrderXML->Kunde->OrdreHode->OrdreLinje->addChild('StatusHB'); //se over.
}
Header('Content-type: text/xml');
echo $OrderXML->asXML();
Gives the following result:
<Ordreimport>
<Kunde>
<..>
<Orderline>
<data>
<data>
</orderline>
</kunde>
</ordreimport>
Also having $OrdreHode= $OrderXML->Kunde->OrdreHode->addChild('OrdreLinje'); inside the loop, like I initually though, gives the same result, except that it also creates an empty <orderline> tag for each additional orderline in the database. Which is ALMOST correct, except all the data ends up in the first <orderline> tag.
You are using the entire XML tree for adding nodes. So the first one will be selected. Use the current generated node instead.
Further more write headers and the XML outside the loop.
while ($kunderad = mysql_fetch_array($HentKunde))
{
$Kunde = $OrderXML->addChild('Kunde');
$KundeInfo = $Kunde->addChild('KundeID', ''); //BD60 - Kundekort - Kundenr
$OrdreHode = $Kunde->addChild('OrdreHode'); //OF14 - Ordrehode
$OrdreLinje = $OrdreHode->addChild('OrdreLinje');
// execute statement to query related data rows here
while ($olrader = mysql_fetch_array($HentOrdrelinje))
{
$OrdreLinje = $OrdreLinje->addChild('StatusHB'); //se over.
}
}
Header('Content-type: text/xml');
echo $OrderXML->asXML();
Note that mysql_ functions are unsafe and obsolete in newer PHP versions. Use mysqli_ or PDO instead.
You do not show how you query the results of the line:
while ($olrader = mysql_fetch_array($HentOrdrelinje))
Without executing the statement related to the current $kunderad within each iteration of the outer loop the inner loop won't query any new datasets. I assume you actually did and cutted this out from the minimal example.

How to get the valid XML notation in php from DB

I have stored below mention XML in a table(MS-SQL DB).
<CUSTOMER>
<CUSTOMERDATA>
<USERID>12691</USERID>
<USERCODE>FFRD991</USERCODE>
<MOBILENO>5645353443</MOBILENO>
<EMAILID>jhfghfghgf#sdf.fh</EMAILID>
<FIRSTNAME>ggdg</FIRSTNAME>
<MIDDLENAME>dfgdfgdf</MIDDLENAME>
<LASTNAME>gdfgdf</LASTNAME>
<ADDRESS></ADDRESS>
<CITY></CITY>
<PINCODE></PINCODE>
<STATENAME></STATENAME>
<SOURCE>Others</SOURCE>
<CREATEDATE>2015-12-01</CREATEDATE>
<STATUS></STATUS>
</CUSTOMERDATA>
</CUSTOMER>
Now I want to fetch this record by php using the following code :
$query = "Select xml_rec from tbl_node where UserId = 12691";
$result = sqlsrv_query($this->db->conn_id, $query);
$row = sqlsrv_fetch_object($result);
//// OR
$row = sqlsrv_fetch_array($result , SQLSRV_FETCH_ASSOC);
echo $row['xml_rec'];
I am getting the following wrong XML . Please note the blank tags.
<CUSTOMER>
<CUSTOMERDATA>
<USERID>12691</USERID>
<USERCODE>FFRD991</USERCODE>
<MOBILENO>5645353443</MOBILENO>
<EMAILID>jhfghfghgf#sdf.fh</EMAILID>
<FIRSTNAME>ggdg</FIRSTNAME>
<MIDDLENAME>dfgdfgdf</MIDDLENAME>
<LASTNAME>gdfgdf</LASTNAME>
<ADDRESS/>
<CITY/>
<PINCODE/>
<STATENAME/>
<SOURCE>Others</SOURCE>
<CREATEDATE>2015-12-01</CREATEDATE>
<STATUS/>
</CUSTOMERDATA>
</CUSTOMER>
How to fix this to show the proper XML ? Thanks for your valuable time.
You don't really use any xml-processing functions here, you simply retrieve a string and display it. The most likely cause of your problem was that some time when you stored this data in your DB, the empty tags got processed from the
<tag></tag>
form into
<tag />
form.
You can check this by connecting to your DB directly (without PHP) and running the query manually.
In any case, as lad2025 pointed out, the two ways of writing empty tags are equivalent so it shouldn't matter for your application.

Updating MySQL from XML file using PHP

I read many useful answers here and the most of them helped me to create script for importing data from XML file. Problem is that this time i have additional part with images url's witch also needs to be updated into MySQL.
For now, i update MySQL with data from XML, after that use other script to download needed images. After website with XML feed changed they structure, i have problem to figure out how to update images url in array into MySQL row so i can download images after that.
Even i choose to download images without updating into MySQL, i also can't download them.
This is XML structure
<ArrayOfUnitDTO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UnitDTO>
<Category>Category name</Category>
<code>863</code>
<Status>Blocked</Status>
<RefNo>12345</RefNo>
<Images>
<Image>
<Title>Community</Title>
<ImageURL>http://imageaddress.com/images/watermark.aspx?imageurl=/uf/1015/GroupUpdate/unit/350/350_Image.jpg&width=640&group=1015&module=1&watermarktype=default&position=Center</ImageURL>
</Image>
<Image>
<Title>Local Area Image</Title>
<ImageURL>http://imageaddress.com/images/watermark.aspx?imageurl=/uf/1015/GroupUpdate/unit/631/631_Image.jpg&width=640&group=1015&module=1&watermarktype=default&position=Center</ImageURL>
</Image>
</Images>
</UnitDTO>
</ArrayOfUnitDTO>
I am i am using this
foreach ($listings ->UnitDTO as $listingInfo) //loop read xml
{
$RefNo = $listingInfo->RefNo;
$Category = $listingInfo->Category;
$code = $listingInfo->code;
$Status = $listingInfo->Status;
mysqli_query($link,"REPLACE INTO UnitDTO (`RefNo`, `Category`, `code`, `Status`) VALUES ('$RefNo', '$Category', '$code', '$Status',)") or die(mysqli_error($link));
}
No metter what i tried, i can't import images url into imageurl MySQL row in array.
to get image url from above xml you have to run one more foreach loop, try something like below code and use it as per your requirement.
foreach ($listings ->UnitDTO as $listingInfo){
$RefNo = $listingInfo->RefNo;
$Category = $listingInfo->Category;
$code = $listingInfo->code;
$Status = $listingInfo->Status;
foreach ($listingInfo->Images->Image as $image){
echo $image->ImageURL;
}
}

How to pass a parsed XML into a mySQL database using PHP?

I have a local server , where i am receiving xml files. The xml files are received just fine but i have problem on how to pass my XML file into my database.
I retrieve the xml file simple as that :
$xml_post = file_get_contents('php://input');
The xml files i receive looks like this :
<city>
<id>1081</id>
<name>athens</name>
<country>Greece</country>
<info>etc etc etc</info>
</city>
I have manually created a database with phpmyadmin with the exact same nodes so i can save everything correctly.
Now i want to insert what i am getting in the database with mysql_query.
Something like this :
mysql_query("INSERT INTO cities (id, city ,country , info)
VALUES (4 , 'athens' , 'greece' , 'etc etc etc'");
But which are the variables that i have stored my xml to use them as values in the statement above? How can i parse the xml file that i have to store all the nodes in variables and then pass them correctly to the database?
Try using simplexml_load_string()
Example usage:
<?php
$xml = '<city>
<id>1081</id>
<name>athens</name>
<country>Greece</country>
<info>etc etc etc</info>
</city>
';
$xml = simplexml_load_string($xml);
//1081
echo $xml->id;
//athens
echo $xml->name;
?>
If you have multiple nodes within your XML each node will be an array of objects:
$xml = '
<citys>
<city>
<id>1081</id>
<name>athens</name>
<country>Greece</country>
<info>etc etc etc</info>
</city>
<city>
<id>1082</id>
<name>somwhere else</name>
<country>Spain</country>
<info>etc etc etc</info>
</city>
</citys>
';
$xml = simplexml_load_string($xml);
//print_r($xml);
foreach($xml->city as $val){
echo $val->name;
}
//or
echo $xml->city[0]->name;
//athens
echo $xml->city[1]->name;
You would need to parse the XML into data readable by PHP, and then use that data in your SQL insert.
PHP SimpleXML Tutorial might be a place to start.

Exporting MySQL data to xml using PHP - HTML encoding and general error BRAIN MELT

Anyone who can answer my question deserves a BIG FAT GOLD MEDAL OF AWESOMENESS!
I'm trying to get the contents of a MySQL table into a nice, easy XML format. I'm running a bit of PHP which works great and I can see XML (Good times). However, in the MySQL table there are a couple of fields which are populated with non-encoded HTML table code. I'm wrapping each field value that I get inside CDATA tags, I've made sure that the xml tags are being closed, but I'm wondering if I'm missing something because it's erroring and I can't see why (Bad times). It looked fine to me, so I tried to open this in Excel (as that's how the client will see it) it claimed that the start tag of "package" was matched with an end tag of "long_description".
http://www.shavesgreensafaris.com/display.php is the page that I'm working on so you can see the data there.
This is the code I'm using...
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = "packages";
$xml .= "<$root_element>";
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<package>";
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//$key holds the table column name
$xml .= "<$key>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "<![CDATA[$value]]>";
//and close the element
$xml .= "</$key>";
}
$xml.="</package>";
}
}
//close the root element
$xml .= "</$root_element>";
//send the xml header to the browser
header ("Content-Type:text/xml");
//output the XML data
echo $xml;
What ON EARTH am I doing wrong?!
EDIT
OK, so there appears to be something that removes one "<" from a long_description tag around line 310 - you can search in the view source if you want to see it as ">long_description>" - something really weird has happened and the tag isn't properly formed. I wasn't entirely sure HOW this could happen as the code I'm using definitely puts opening and closing angle brackets on all $keys. It only happens once, but it seems to stuff everything else up.
Anyone know why this might be occurring?
Any help HUGELY appreciated, and thanks in advance!
Gem
I feel that DOM would be the way to approach this. The code may look somewhat more cumbersome at first glance, but it will take care of all the output formatting for you:
<?php
// The names of the root node and the node that will contain a row
$root_element = "packages";
$row_element = "package";
// Create the DOMDocument and the root node
$dom = new DOMDocument('1.0', 'utf-8');
$rootNode = $dom->appendChild($dom->createElement($root_element));
// Loop the DB results
while ($row = mysql_fetch_assoc($result)) {
// Create a row node
$rowNode = $rootNode->appendChild($dom->createElement($row_element));
// Loop the columns
foreach ($row as $col => $val) {
// Create the column node and add the value in a CDATA section
$rowNode->appendChild($dom->createElement($col))
->appendChild($dom->createCDATASection($val));
}
}
// Output as string
echo $dom->saveXML();

Categories