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.
Related
Say, I have the following php code:
<?php
$resultXML = "<root><book></book></root>";
$resultXML = new SimpleXMLElement($resultXML);
?>
How can I insert the following XML: <car><bmw></bmw></car> such that I get <root><car><bmw></bmw></car><book></book></root>
Basically, I want to generic solution to insert an element (with its children, grandchildren etc) in an existing XML. Any help?
Try this
$resultXML = new SimpleXMLElement('<root><book></book></root>');
$car=$resultXML->addChild('car');
$car->addChild('bmw');
$resultXML->asXML('path/to/save/abc.xml');
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);
I have made a search html page using IMDBAPI to create an xml file for that item I search. Then I have a php file that will parse through that file and only pull the data I want from the xml file to display. Everything seems to be working as I am getting a blank white page. The issue is that nothing is displaying.
Part of the XML
<IMDBDocumentList>
<item>
<rating>8.7</rating>
<rating_count>10301</rating_count>
<year>1999</year>
<genres>
<item>Animation</item>
<item>Action</item>
<item>Adventure</item>
<item>Comedy</item>
<item>Drama</item>
<item>Fantasy</item>
<item>Romance</item>
</genres>
<rated>PG</rated>
<title>Wan pîsu: One Piece</title>
<imdb_url>http://www.imdb.com/title/tt0388629/</imdb_url>
<directors>
<item>Kônosuke Uda</item>
</directors>
<actors>
<item>Mayumi Tanaka</item>
<item>Kazuya Nakai</item>
<item>Akemi Okamura</item>
<item>Kappei Yamaguchi</item>
<item>Mahito Ôba</item>
<item>Hiroaki Hirata</item>
<item>Colleen Clinkenbeard</item>
<item>Ikue Ôtani</item>
<item>Chikao Ôtsuka</item>
<item>Yuriko Yamaguchi</item>
<item>Luci Christian</item>
<item>Christopher Sabat</item>
<item>Sonny Strait</item>
<item>Kazuki Yao</item>
</actors>
PHP Parse
$lib = simplexml_load_file("test.xml");
$xml = $lib->IMDBDocumentList->item;
$rating = $xml->rating;
$year = $xml->year;
print $rating;
print $year;
IMDBDocumentList is your root node, so you don't need to address it:
$xml = $lib->item;
I have source XML here: http://www.grilykrby.cz/rss/pf-heureka.xml. I want to use this xml feed and create another modified on my own server. I would like to change every node CATEGORYTEXT which contains word Prislusenstvi. I just tried something but I got only the listing of all categories without changing XML :-(
Here is the example of my code. The row $kategorie="nejaka kategorie"; doesn't work.
<?php
$file = "http://www.grilykrby.cz/rss/pf-heureka.xml";
$xml=simplexml_load_file($file);
foreach ($xml->xpath('//SHOPITEM/CATEGORYTEXT') as $kategorie) {
echo $kategorie."<br />";
$kategorie="nejaka kategorie";
}
file_put_contents('test.xml', $xml->asXML());
?>
$kategorie is just a temp variable used in the loop which contains a copy of the data returned by xpath query. You would need to actually set the value directly in the $xml object.
I would personally also consider doing a str_replace or preg_replace within the XML content itself before parsing it into a simpleXML object.
Final Accepted Answer
<?php
$xml = simplexml_load_file('http://www.grilykrby.cz/rss/pf-heureka.xml');
$i=0;
foreach($xml -> SHOPITEM as $polozka) {
if ($polozka -> CATEGORYTEXT == "Příslušenství") $xml -> SHOPITEM[$i] -> CATEGORYTEXT = "Some other text";
$i++;
}
?>
I dont seem to quite understand how xml_parse works. What i was doing was getting the contents of the xml file, create a parser, and pass it into xml_parse(). I dont know what to do after that. I was thinking that in my case, $xml was the array i can now iterate through. I was trying to see how i would parse my data.
$fp = file_get_contents("memberdata.xml");
echo "pre-create";
$xml = xml_parser_create();
echo "pre-parse";
$status = xml_parse($xml,$fp);
if(!$status){
die("Error parsing data from $fp into $xml");
}
echo "pre XML posting";
echo "<br />".$xml."<br />";
print_r($xml);
xml_parser_free($xml);
I cant seem to figure out how to access this.
Sample xml data is as follows:
<currentTime>2012-09-05 03:43:25</currentTime>
<result>
<rowset name="members" key="characterID" columns="characterID,name,startDateTime,baseID,base,title,logonDateTime,logoffDateTime,locationID,location,shipTypeID,shipType,roles,grantableRoles">
<row ..>
</rowset>
</result>
<cachedUntil></cashedUntil>
Instead of using the base tools, using one of the toolkits, SimpleXML will alleviate a lot of the frustrations. The answer to this question is redone using SimpleXML.
$fp = file_get_contents("memberdata.xml");
$eve = new SimpleXMLElement($fp);
$cols = $eve->{'result'}->rowset['columns'];
//I put result in {} because result is a special character in php.
$cols = explode(",",$cols);
foreach ($cols as $c){
echo "".$c."<br />";
}
//output is printed to screen