Adding data from php/mysql query into an XML file - php

I want to add/display data from querying from the database and add it into an XML file.
Example, I have a table_persons which has a name and age. I create a mysql query to get its name and age. Then simply put the data(name and age of persons) into an XML file.
How would you do that? Or is it possible?

I suggest you use DomDocument and file_put_contents to create your XML file.
Something like this:
// Create XML document
$doc = new DomDocument('1.0', 'UTF-8');
// Create root node
$root = $doc->createElement('persons');
$root = $doc->appendChild($root);
while ($row = mysql_fetch_assoc($result)) {
// add node for each row
$node = $doc->createElement('person');
$node = $root->appendChild($node);
foreach ($row as $column => $value) {
$columnElement = $doc->createElement($column);
$columnElement = $node->appendChild($columnElement);
$columnValue = $doc->createTextNode($value);
$columnValue = $columnElement->appendChild($columnValue);
}
}
// Complete XML document
$doc->formatOutput = true;
$xmlContent = $doc->saveXML();
// Save to file
file_put_contents('persons.xml', $xmlContent);

<?php
[snip] //database code here
$f = fopen('myxml.xml', 'a+');
foreach($row = mysqli_fetch_assoc($resultFromQuery))
{
$str = "<person>
<name>{$row['name']}</name>
<age>{$row['age']}</age>
</person>\n";
fwrite($f, $str);
}
fclose($f);
?>
Assuming you use mysqli, this code works. If not, suit to fit. In the fopen function call, the a+ tells it to open it for reading at writing, placing the pointer at the end of the file.
Best of luck.

Related

counting & loading correctly childrens from an xml file

hello i have tried and nothing will happen...
i will count the childs from an xml file via php
everthing is ok but i dont get, - load correctly this stupid xml file into my page =
here's the script simply --
$url123 = 'http://steamcommunity.com/id/ProJaCore/stats/GarrysMod/?xml=1';
$data123 = file_get_contents($url123);
$xml = simplexml_load_string($data123);
$elem = new SimpleXMLElement($xml);
foreach ($elem as $achievements) {
print $achievements->count().'<br>';
}
Do this:
$url123 = 'http://steamcommunity.com/id/ProJaCore/stats/GarrysMod/?xml=1';
$data123 = file_get_contents($url123);
$elem = new SimpleXMLElement($data123);
foreach ($elem as $achievements) {
print $achievements->count().'<br>';
}
In your code you're creating a SimpleXMLElement object in $xml, then trying to create another one in $elem using the $xml object.
See the complete reference: http://www.php.net/manual/en/book.simplexml.php

Adding xml node on top of file or reverse the loop

I am using xml. Reading the xml-document works fine, adding nodes works fine to but I want the node to add on top of the xml file. Is this possible or is this a nogo?
The reason I want this is because when I display the xml file I want the last added node, displayed as the newest one, on top.
I display the xml with this loop:
foreach($xml->xpath("//user[#id='12345678']") as $user){
foreach($user->children() as $action => $data){
echo"<li>";
echo $data->content;
echo $data->date;
echo"</li>";
}
}
If there is a way to reverse the loop or another way I'm fine with that to, it doesn't have to be adding the first node on top. Below are the file how I add the node and the structure of the xml-file.
Does anyone have an idea how to solve this?
addxml.php
<?php
$file = "actielijst.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");
// get document element
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
$root = $xml->documentElement;
$content = $xml->createElement("content");
$contentText = $xml->createTextNode("Nieuwe Factuur Mei");
$content->appendChild($contentText);
$date = $xml->createElement("date");
$dateText = $xml->createTextNode("23-12-2010");
$date->appendChild($dateText);
$action = $xml->createElement("action");
$action->appendChild($date);
$action->appendChild($content);
$root->appendChild($action);
$xml->save("actielijst.xml") or die("Error");
?>
actielijst.xml
<?xml version="1.0"?>
<userid>
-------> Insert new action here <------
<action>
<date>23-01-2010</date>
<content>nieuwe factuur</content>
</action>
<action>
<date>23-01-2010</date>
<content>karten op 01-02</content>
</action>
</userid>
You can use xpath to capture every parent node (action in your case) and then reverse the array...
$users_arr = array_reverse($xml->xpath("action"));
Now you can loop through this array!
This will helps
<?php
$file = "actielijst.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));
$xml = simplexml_load_string($str);
$action = $xml->addChild('action');
$action->addChild('content','sundar');
$action->addChild('date','23-12-2010');
header('content-type: application/xml');
echo $xml->saveXML();

PHP simpleXML, instead of appending, writes over everything

I have an ongoing xml file, that when I call a php function to add a new child, it loops through an array of strings and queries a db to add a new child to the document and save it as the current string in the array. However, it is not appending, it is overwriting everything. Do I need to load the file first? and check if it exists?
function createUnitsXML($units,$wcccanumber,$mysqli) {
// Delete whitespaces and create an array of units assigned to call
$unit = preg_replace('/\s+/', '', $units);
$unitsarray = explode(",",$unit);
for ($i = 0; $i < count($unitsarray); $i++) {
$xml = new SimpleXMLElement('<xml/>');
$query = "SELECT * FROM calls WHERE wcccanumber = '$wcccanumber'";
$result = $mysqli->query($query);
while($row = mysqli_fetch_assoc($result)) {
$draw = $xml->addChild('call');
$draw->addChild('wcccanumber',$row['wcccanumber']);
$draw->addChild('currentcall',$row['call']);
$draw->addChild('county',$row['county']);
$draw->addChild('id',$row['id']);
$draw->addChild('location',$row['location']);
$draw->addChild('callcreated',$row['callcreated']);
$draw->addChild('station',$row['station']);
$draw->addChild('units',$row['units']);
$draw->addChild('calltype',$row['calltype']);
$draw->addChild('lat',$row['lat']);
$draw->addChild('lng',$row['lng']);
$draw->addChild('inputtime',$row['inputtime']);
}
$fp = fopen("xml/units/$unitsarray[$i].xml","wb");
fwrite($fp,$xml->asXML());
fclose($fp);
}
echo "--- Created units XML document for call: $wcccanumber";
echo "</br>";
}
$fp = fopen("xml/units/$unitsarray[$i].xml","wb");
By opening the file as "wb", you are truncating the file to write. Try using "ab" (write-only, appends to end of file) or "ab+" (read or write, appends to end of file) instead.

Write to a file using PHP

Bassicly what I want to do is using PHP open a xml file and edit it using php now this I can do using fopen() function.
Yet my issue it that i want to append text to the middle of the document. So lets say the xml file has 10 lines and I want to append something before the last line (10) so now it will be 11 lines. Is this possible. Thanks
Depending on how large that file is, you might do:
$lines = array();
$fp = fopen('file.xml','r');
while (!feof($fp))
$lines[] = trim(fgets($fp));
fclose($fp);
array_splice($lines, 9, 0, array('newline1','newline2',...));
$new_content = implode("\n", $lines);
Still, you'll need to revalidate XML-syntax afterwards...
If you want to be able to modify a file from the middle, use the c+ open mode:
$fp = fopen('test.txt', 'c+');
for ($i=0;$i<5;$i++) {
fgets($fp);
}
fwrite($fp, "foo\n");
fclose($fp);
The above will write "foo" on the fifth line, without having to read the file entirely.
However, if you are modifying a XML document, it's probably better to use a DOM parser:
$dom = new DOMDocument;
$dom->load('myfile.xml');
$linenum = 5;
$newNode = $dom->createElement('hello', 'world');
$element = $dom->firstChild->firstChild; // skips the root node
while ($element) {
if ($element->getLineNo() == $linenum) {
$element->parentNode->insertBefore($newNode, $element);
break;
}
$element = $element->nextSibling;
}
echo $dom->saveXML();
Of course, the above code depends on the actual XML document structure. But, the $element->getLineNo() is the key here.

Format XML Document created with PHP - DOMDocument

I am trying to format visually how my XML file looks when it is output. Right now if you go here and view the source you will see what the file looks like.
The PHP I have that creates the file is: (Note, $links_array is an array of urls)
header('Content-Type: text/xml');
$sitemap = new DOMDocument;
// create root element
$root = $sitemap->createElement("urlset");
$sitemap->appendChild($root);
$root_attr = $sitemap->createAttribute('xmlns');
$root->appendChild($root_attr);
$root_attr_text = $sitemap->createTextNode('http://www.sitemaps.org/schemas/sitemap/0.9');
$root_attr->appendChild($root_attr_text);
foreach($links_array as $http_url){
// create child element
$url = $sitemap->createElement("url");
$root->appendChild($url);
$loc = $sitemap->createElement("loc");
$lastmod = $sitemap->createElement("lastmod");
$changefreq = $sitemap->createElement("changefreq");
$url->appendChild($loc);
$url_text = $sitemap->createTextNode($http_url);
$loc->appendChild($url_text);
$url->appendChild($lastmod);
$lastmod_text = $sitemap->createTextNode(date("Y-m-d"));
$lastmod->appendChild($lastmod_text);
$url->appendChild($changefreq);
$changefreq_text = $sitemap->createTextNode("weekly");
$changefreq->appendChild($changefreq_text);
}
$file = "sitemap.xml";
$fh = fopen($file, 'w') or die("Can't open the sitemap file.");
fwrite($fh, $sitemap->saveXML());
fclose($fh);
}
As you can tell by looking at the source, the file isn't as readable as I would like it to be. Is there any way for me to format the nodes?
Thanks,
Levi
Checkout the formatOutput setting in DOMDocument.
$sitemap->formatOutput = true
not just PHP, there is a stylesheet for XML: XSLT, which can format XML into sth looks good.

Categories