append or create a new xml file from php - php

I have a php file which is created to append data to a xml but if the file is not there it is supposed to create the file.But when I run the php it gives me output that I didn't expect which is added in the end of the question. XML file is not getting created. The following is the php file.
<?php
header('Content-Type: text/xml');
function createXML($doc) {
$markers = $doc->createElement('markers');
$markers = $doc->appendChild($markers);
}
$url = '../../data/data.xml';
$lat = "bla1";
$lng = "bla2";
$address = "bla3";
$doc = new DomDocument();
if (!file_exists($url)){
createXML($doc);
}
else {
$doc->preserveWhiteSpace = FALSE;
$doc->load($url);
}
$markers = $doc->getElementsByTagName('markers')->item(0);
$marker = $doc->createElement('marker');
$marker = $markers->appendChild($marker);
$marker->setAttribute("lat", $lat);
$marker->setAttribute("lng", $lng);
$marker->setAttribute("address", $address);
$doc->formatOutput = true;
$doc->save($url);
?>
when I run the php file I get the following output
Fatal error : Call to a member function appendChild() on a non-object in
/home[...]/saveMarkers.php on line 30
can you tell me what I have done wrong in here thank you in advance

I just tested your code is fine and doing what is expected, You don't need to use header if you don't want to echo
anyway verify you have permissions to write in the destination directory

Related

When appending to the end of the XML, the formatOutput doesn't work but when first creating the file, the formatOutput works fine

This may sound pretty basic but right now I am very confused.
Right now I'm using php to create an XML file, first I check if the file exists, and if he doesn't I create the file with the first entry created, but if the XML file does already exist, then ill will just append the data. The data is being appended when needed and the file is being created without any bugs, but the only small problem I am having is that when I append the data to the end of the file, it won't format to regular waterfall format it has, instead it just appends it in one line. Here is my php code:
<?php
$id = $_POST['id_from'];
$id_to = $_POST['userid_to'];
$content = $_POST['message'];
$time = $_POST['time'];
$xml = new DOMDocument("1.0");
$xml->formatOutput = true;
$filename = 'chats/'.$id.'-'.$id_to.'.xml';
if(file_exists($filename)){
$xml->load($filename);
$messages = $xml->getElementsByTagName('messages')->item(0);
$message = $xml->createElement("message");
$messages->appendChild($message);
$content = $xml->createElement("content", $content);
$message->appendChild($content);
$to = $xml->createElement("to", $id_to);
$message->appendChild($to);
$from = $xml->createElement("from", $id);
$message->appendChild($from);
}else{
//creating root
$messages = $xml->createElement('messages');
$xml->appendChild($messages);
$message = $xml->createElement("message");
$messages->appendChild($message);
$content = $xml->createElement("content", $content);
$message->appendChild($content);
$to = $xml->createElement("to", $id_to);
$message->appendChild($to);
$from = $xml->createElement("from", $id);
$message->appendChild($from);
}
$xml->save($filename) or die("error");
?>
And below is a picture of my xml file.
Thank you very much!
Image of my xml file
You need to disabled whitespaces preservation before loading the file, so DOMDocument can do its own business without trying to keep the original format in place.
$xml = new DOMDocument("1.0");
$xml->preserveWhiteSpace = false ;
$xml->formatOutput = true;

Generate xml file using php but ampersand is not displaying

My php code generate xml file but the line that has the ampersand in the url is not displaying. Below is the php code
$dom = new DOMDocument('1.0','UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement('journal');
$dom->appendChild($root);
$journal_metadata = $dom->createElement('journal_metadata');
$dom->appendChild($journal_metadata);
$issue_doi = $dom->createElement('doi', '11');
$issue_doi_data->appendChild($issue_doi);
$issue_resource = $dom->createElement('resource', 'http://localhost/fo/issues.php?jid=1&issueID=155');
$issue_doi_data->appendChild($issue_resource);
echo '<xmp>'. $dom->saveXML() .'</xmp>';
$dom->save('result.xml') or die('XML Create Error');
The line that has "url with ampersand" isn't displaying because $issue_doi_data variable which should contain that url was not declared and not appended to the initial document $dom.
Secondly, in case of getting warning message "unterminated entity reference" you may use htmlentities() (or htmlspecialchars()) for escaping supplied value.
Change your code as shown below:
$dom = new \DOMDocument('1.0','UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement('journal');
$dom->appendChild($root);
$journal_metadata = $dom->createElement('journal_metadata', '...');
$root->appendChild($journal_metadata);
// modify this line with your prefered name and value
$issue_doi_data = $dom->createElement('doi_data', '');
$issue_doi = $dom->createElement('doi', '11');
$issue_doi_data->appendChild($issue_doi);
$issue_resource = $dom->createElement('resource', htmlspecialchars('http://localhost/fo/issues.php?jid=1&issueID=155'));
$issue_doi_data->appendChild($issue_resource);
$root->appendChild($issue_doi_data);
// save xml into file
$dom->save('result.xml') or die('XML Create Error');
// outputting xml file content
echo '<xmp>'. html_entity_decode(file_get_contents('result.xml')) .'</xmp>';
// the output:
<?xml version="1.0" encoding="UTF-8"?>
<journal>
<journal_metadata>...</journal_metadata>
<doi_data>
<doi>11</doi>
<resource>http://localhost/fo/issues.php?jid=1&issueID=155</resource>
</doi_data>
</journal>
You will have to "escape" it. Try using: & instead of just &.

How can I return an XML message from PHP?

I am having some trouble mixing PHP with XML.
I currently have a PHP file that takes variables from the URL string and I need to calculate something based on these variables, and then return the output in an XTML format.
I currently have my main config file that links to my xml generating file:
include('Xml.php');
$x = new xml();
$x->generate();
And my XML generating file is as follows:
<?php
Class XML {
public function generate() {
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('conv');
$root = $doc->appendChild($root);
$at = $doc->createElement('at');
$at = $root->appendChild($at);
$text = $doc->createTextNode("hi");
$text = $at->appendChild($text);
echo $doc->saveXML();
}
}
?>
But this doesn't work - what am I doing wrong here - I know it's probaby obvious but I am new to XML and can't seem to get it working!
Should I be doing it differently? If so ... how?
I've just tested your class with following code:
$xml = new XML();
$xml->generate();
And I've got this result:
[vyktor#grepfruit tmp]$ php test.php
<?xml version="1.0"?>
<conv>
<at>hi</at>
</conv>
So your class works just fine and your error is somewhere else, eg. including wrong file.
Turn on error_reporting and paste errors in comment.

XML Parsing Error: XML or text declaration not at start of entity in php

Hi I am generating a xml file in php but getting error
XML Parsing Error: XML or text declaration not at start of entity
My code is---
<?php require_once('../../settings.php');
header("Content-type:text/xml");
$dom=new DOMDocument('1.0');
$dom->formatOutput = true;
$id=(int)$_GET['imageid'];
$query="select * from tbl_image_gallery where imageId='$id' ORDER BY gallId DESC ";
$select=mysql_query($query);
$content = $dom->appendChild($dom->createElement('content'));
while($res=mysql_fetch_array($select))
{
$image = $content->appendChild($dom->createElement('image'));
$small_image_path = $image->appendChild($dom->createElement('small_image_path'));
$small_image_path->appendChild($dom->createTextNode("image_gallery/load/images/small/".$res['image']));
$big_image_path = $image->appendChild($dom->createElement('big_image_path'));
$big_image_path->appendChild($dom->createTextNode("image_gallery/load/images/big/".$res['image']));
$description = $image->appendChild($dom->createElement('description'));
$description->appendChild($dom->createCDATASection($res['description']));
}
echo $test1 = $dom->saveXML();
?>
After search on google i found that it is problem related to space before
I remove space but not getting expected result.
Remove below line and try if the error message has gone Then surely you have space or something else outputted before in the settings.php file.
header("Content-type:text/xml");
Check settings.php file and remove the spaces if you have. Note that if settings.php file is also including some other files you have to check space in those file also.
Use ob_clean(); before echo $test1 = $dom->saveXML();

Problem with loading remote XML file

I'm trying to load a remote xml file using php.
This is my code:
$doc = new DOMDocument();
$doc->load($this->xml_file);
$file = $doc->getElementsByTagName('file');
$totalFiles = $file->length;
echo $totalFiles;
The remote xml file link is:
http://localhost/script/index.php?act=xml
This is the code in index.php:
$xml = '<?xml version="1.0"?><MultimediaGallery>';
$query = mysql_query('SELECT `id`,`image`,`desc` FROM `'
.confitem('database','prefix').'table` ORDER BY `id` DESC LIMIT '
.$start.','.$limit);
while($result = mysql_fetch_array($query))
{
$img = unserialize($result['image']);
$desc = unserialize($result['desc']);
$xml .= '<file type="photo"><thumb>'
.settings('site','url').'/'.OPATH_APPFOLDER.'/'
.OPATH_UPFOLDER.'/wallpapers/thumbs/'.$img[0].'</thumb><source>'
.settings('site','url')
.'/'.OPATH_APPFOLDER.'/'.OPATH_UPFOLDER
.'/wallpapers/'.$img[0].'</source><description>'
.$desc[$_SESSION['languagecode']].'</description></file>';
}
$xml .= '</MultimediaGallery>';
header("content-type: text/xml");
echo $xml;
When I visit this xml file link direct in the browser .. it's output to me xml file with this style :
<?xml version="1.0"?><MultimediaGallery><file type="photo"><thumb>http://localhost/script/application/data/wallpapers/thumbs/1116205566_42ce0841ab_s.jpg</thumb><source>http://localhost/script/application/data/wallpapers/1116205566_42ce0841ab_s.jpg</source><description>dfdfdfdf</description></file></MultimediaGallery>
When I execute the xml function which uses the dom to load the xml file I get this error:
Warning: DOMDocument::load()
[domdocument.load]: Extra content at
the end of the document in
http://localhost/script/index.php,
line: 2 in
C:\AppServ\www\script\application\libraries\wallpapers\multimedia.class.php
on line 46
Why is this happening?
Update:
I used dom to create the xml instead:
$xml = new DOMDocument('1.0');
$root = $xml->createElement('MultimediaGallery');
$xml->appendChild($root);
$query = mysql_query('SELECT `id`,`image`,`desc` FROM `'.confitem('database','prefix').'backgrounds` ORDER BY `id` DESC LIMIT '.$start.','.$limit);
while($result = mysql_fetch_array($query))
{
$img = unserialize($result['image']);
$desc = unserialize($result['desc']);
$element = $xml->createElement('file');
$root->appendChild($element);
$attr = $xml->createAttribute('type');
$element->appendChild($attr);
$attr_text = $xml->createTextNode('photo');
$attr->appendChild($attr_text);
$thumb = $xml->createElement('thumb');
$element->appendChild($thumb);
$thumb_text = $xml->createTextNode(settings('site','url').'/'.OPATH_APPFOLDER.'/'.OPATH_UPFOLDER.'/wallpapers/thumbs/'.$img[0]);
$thumb->appendChild($thumb_text);
$source = $xml->createElement('source');
$element->appendChild($source);
$source_text = $xml->createTextNode(settings('site','url').'/'.OPATH_APPFOLDER.'/'.OPATH_UPFOLDER.'/wallpapers/'.$img[0]);
$source->appendChild($source_text);
$description = $xml->createElement('description');
$element->appendChild($description);
$description_text = $xml->createTextNode($desc[$_SESSION['languagecode']]);
$description->appendChild($description_text);
}
header("content-type: text/xml");
echo $xml->saveXML();
But it still gives me the same error. I noticed some thing though, I tried to copy my output xml and save it in a file and read it using the dom parser and the result was that it's read successfully.
But when I try parsing the xml output by the php file then it throws an error.
Your XML is not well-formed. E.g there is something wrong with it.
Try to avoid making XML by concatenating strings because this will happen. You can use DomDocument you make XML as well as read it and manipulate it.
Make sure you have no leading or trailing white space in your XML generating script.
You should also be using CDATA

Categories