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
Related
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 &.
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
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
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();