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();
Related
The below code successfully saves the child div but also saves some numbers in the file at the end. I think its the bytes of data present, how do i get rid of the numbers it saves?
$file = '../userfolders/'.$email.'/'.$ongrassdb.'/'.$pagenameselected.'.php';
$doc = new DOMDocument();
$doc->load($file);
$ele = $doc->createElement('div', $textcon);
$ele ->setAttribute('id', $divname);
$ele ->setAttribute('style', 'background: '.$divbgcolor.'; color :'.$divfontcolor.' ;display : table-cell;');
$element = $doc->getElementsByTagName('div')->item(0);
$element->appendChild($ele);
$doc->appendChild($element);
$myfile = fopen($file, "a+") or die('Unable to open file!');
$html = $doc->save($file);
fwrite($myfile,$html);
fclose($myfile);
I don't want to use saveHTML nor saveHTMLFile because it creates multiple instances of the divs and adds html tags to it.
$doc->load($file);
...
$myfile = fopen($file, "a+") or die('Unable to open file!');
$html = $doc->save($file);
fwrite($myfile,$html);
fclose($myfile);
The $doc->save() method saves the DOM tree to the file, and returns the number of bytes it wrote to the file. This number is stored in $html and is then append to the same file by fwrite().
Just remove the fopen(), fwrite() and fclose() calls.
I removed the last two lines and it solved the issue
fwrite($myfile,$html);
fclose($myfile);
I would like to get the contents of a div with ID content using PHP, and write the contents to a text file.
Here is some code that I tried:
<?php
$html = file_get_content('www.example.com');
$divContent = $html->find('div#contentArea', 0)->plaintext;
$file = fopen("newfile.txt", w);
fwrite($file, $divContent);
fclose($file);
?>
this code isn't working that says some file_get_content error..
also tried this one
<?php
$html = file_get_html('http://www.example.com/')->plaintext;
$divContent = $html->find('div#contentArea', 0)->plaintext;
$file = fopen("newfile.txt", w);
fwrite($file, $divContent);
fclose($file);
?>
I have needed to do this on many occasions due to site maintenance and error logging. PHP Manual explains further http://php.net/manual/en/domdocument.getelementbyid.php
BASIC EXAMPLE
<?php
$page = file_get_contents('example.html');
$doc = new DOMDocument();
$doc->loadHTML($page);
$node = $doc->getElementById('thisone');
echo $doc->saveHtml($node), PHP_EOL;
?>
What error throwed by file_get_content ? Maybe it's source, of your problem.
For selecting I used phpquery library
<?php
$code = file_get_contents('http://some-url-here');
$document = phpQuery::newDocument($code);
$inner = $document->find('div.hentry')->html();
?>
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.
Is it possible to save the below output to an XML file as its currently just displayed in the source?
$host = "localhost"; // host name
$user = "#"; // database user name
$pass = "#"; // database password
$database = "#"; // database name
// connecting to database
$connect = #mysql_connect($host,$user,$pass)or die (#mysql_error());
// selecting database
#mysql_select_db($database,$connect) or die (#mysql_error());
// default header(don't delete)
header("Content-Type: text/xml;charset=iso-8859-1");
echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// mytable = your content table name
$query = #mysql_query("SELECT * FROM urls");
while($row = #mysql_fetch_array($query)){
// [url] = content url
$url = $row['url'];
// [time] = content date
$date = date("Y-m-d", $row['time']);
// NO CHANGES BELOW
echo
'<url>
<loc>' . $url .'</loc>
<lastmod>'. $date .'</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
';
}
echo '</urlset>';
I know I can use .htaccess to make the file be seen as an XML format however I want the data to be saved onto an actual file.
You could try changing each echo to append the line to a string variable, for example:
// Instead of
echo '<?xml version="1.0"?>';
echo '<url>';
// etc.
$xml = '<?xml version="1.0"?>';
$xml .= '<url>';
// and so on
Then use one of the file functions to save to a file. file_put_contents is a simple method:
file_put_contents("/path/to/file.xml", $xml);
A more robust solution, if you want to take this further, could be to use the DOM module to build the XML structure:
$document = new DOMDocument("1.0");
$root = $document->createElement("urlset");
$root->setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
$document->appendChild($root);
while ($row = mysql_query($query)) {
$item = $document->createElement("url");
$root->append($item);
// etc.
}
echo $document->saveXML();
NOTE: This answer assumes that by "save file" you mean "trigger the Save As dialog in the browser when someone views the page".
text/xml isn't really the correct content-type. You really should at least application/xml for generic XML or the appropriate content type for XML sub-formats such as RSS or docx.
If you want to trigger a file download dialog in the client browser, then you also need to send a content-disposition header that tells the browser that you want it to download the file and give a preferred filename.
There are some issues with your code that need addressing too.
Overuse of # for error suppression. This is a bad idea for a huge variety of reasons. Remove the # operators and handle any generated errors in a more robust way.
Your character encoding heading specifies one character set (latin-1) but your XML preamble specifies a totally different one (UTF-8). That's a recipe for disaster.
Use output buffers
ob_start();
... do everything you actually did before ...
$content = ob_get_contents();
ob_end_clean();
//Write to a file
file_put_contents('filename.xml', $content);
And thats all...
Using fwrite it should be straight forward :
$f = fopen('data.xml', 'w'); //open a file for writing
fwrite($f, $myxmltext); // write some things to it
fclose($f); // close it when finished
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.