Can i use php loops in xml file to list out a list of number incremented file names such as file 1.jpg file2.jpg file3.jpg etc to save me having to manually typing it out.
If so, how do I do this and what doctype etc would the xml file need to have to make it display the loop?
Your question is a little vague, I can't work out if you're trying to read an XML file or write to it.
Assuming you want to read an XML file, and assuming your XML looks a little like this:
<?xml version="1.0" encoding="utf-8" ?>
<rootnode>
<images>
<image>file_1.jpg</image>
<image>file_2.jpg</image>
<image>file_3.jpg</image>
</images>
</rootnode>
you could use SimpleXML to either load the XML file or to load the XML as a string and then return an object to loop through.
http://php.net/manual/en/ref.simplexml.php
Your PHP might look something like this:
if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');
foreach($xml->images AS $image) {
echo $image;
}
} else {
exit('Failed to open test.xml.');
}
What I would do is point to a .php file that outputs XML. All you need to do that is send a header("Content-Type: text/xml"); and make sure you add the at the top of your output.
Here's an example:
<?php
header("Content-Type: text/xml");
print "<?xml version=\"1.0\"?>";
print "<rootNode>";
for(your loop stuff here) {
print "<node>" . $yourDataHere . "</node>";
}
print "</rootNode>";
?>
Related
I originally had a php file pulling in data from another php file. However, I have to change the second php file to an xml file. My question is, how do I read the string between certain tags in the php file using SimpleXML. For Example, here is my XML file:
<?xml version="1.0" encoding="UTF-8"?>
<XMLExample>
<Name>ExampleName</Name>
<Info>ExampleInfo</Info>
<KMLFile>ExampleKML</KMLFile>
</XMLExample>
I previously had this in my php file:
if(strlen($KMLFile)>0){
#echo "<a id=\"links\" href=\"/$place/Area/$KMLFile\">KML File</a> \n";
echo "<a id=\"links\" href=\"/media/$place/markup/xml/$KMLFile\">KML File</a> \n";
}
What I can't figure out is how to change the php code to read the data from the XML file. Any help would be greatly appreciated! Thanks!
Use this code. note.xml is your .xml file.
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->Name.'<br>';
echo $xml->Info.'<br>';
echo $xml->KMLFile;
?>
maybe someone can help me, i provide xml files witch are generated from a PHP DB query and each xml file has a unique name. Now i want to prepare a function like "get the latest xml file" but I don't know whats the best way!
$xml = simplexml_load_file('test.xml');
I found this function but there i have to know the exact name!
or ist something like this possible:
$xml = simplexml_load_file('test.php');
and in the test.php i have a function to get the last name, but how to i provide the xml data?
Some keywords how i can find a solution in google would be very helpful!
The first parameter to that function is a string of the filename. The file should be the XML file to load, so you cant use another php file.
http://php.net/manual/en/function.simplexml-load-file.php
So you need to get the filename as a string first by using a variable. You should be able to copy the code in your test.php file, then save the filename instead of echoing it out. Then you use that variable when loading the xml file.
e.g.
function get_latest_filename()
{
//contents of your test.php file should set this variable
$latest_filename = 'the_latest_file.xml';
return $latest_filename;
}
$latest = get_latest_filename();
$xml = simplexml_load_file($latest);
here the finish solution that worked for me
i protected the directory with .htaccess and inside i store all my generated xml files and also the getLastXml.php file!
the getLastXml.php
function get_last_file() {
$lastFileTime = 0;
foreach (glob("*.xml") as $filename) {
if ($lastFileTime<filemtime($filename))
{
$lastFileTime = filemtime($filename);
$lastFileName = $filename;
}
}
return $lastFileName;
}
$lastXmlFile = get_last_file();
header ("Content-Type:text/xml");
echo file_get_contents($lastXmlFile);
the functions get_last_file() returns the name of the latest created xml file and
header ("Content-Type:text/xml");
displays xml in the php file
echo file_get_contents($lastXmlFile);
loads the content of the xml file and display it
simplexml_load_file("http://username:passwort#urlToTheDirectory/getLastXml.php");
loads the xml data with
I have been working on a project that displays data in an XML file. (It's kind of like an API). I know how to parse XML with PHP, and how to make an XML file in PHP, but they don't work together. :)
Basically, I have two files: parse.php and xml.php.
xml.php grabs info from a MySQL database, and outputs it as XML.
parse.php loads and parses xml.php and outputs it as HTML.
If I run parse.php, it does not load xml.php. However, if I copy the outputted XML (from xml.php) and save it as a xml.xml file (and change the filename in parse.php to 'xml.xml') it works. I'd really appreciate any help.
Content of parse.php:
<?php
$doc = "xml.php";
$doc = #simplexml_load_file($doc) or die("Server Error: Recipe not found!");
$title = $doc->title;
echo $title
?>
Content of xml.php:
<?php
header("Content-type: text/xml");
$dbc = mysql... //gets data from database
echo "<!DOCTYPE..."; //xml stuff here
echo "<title>" . $dataFromMySQL . "</title>";
?>
The database connection works, and the DOCTYPE in the XML is ok, so that's not the problem.
Again, I only get the problem when I generate XML dynamically using PHP. If it's a .XML file, it works fine.
Can anyone help me?
Thanks.
simplexml_load_file will try to actually load the php contents of the xml.php file. It will not run that file first. You need to do some rewriting or use this ugly solution:
ob_start();
include 'xml.php';
$xml = ob_get_clean();
$doc = simplexml_load_string($xml);
//...
NOTE: I like #lonesomeday's proposed solution better, it will just require more rewriting.
#simplexml_load_file($doc);
That is where your problem is. This does not execute xml.php, but attempts to parse that file -- the PHP code that you've written -- as XML. Obviously (since it isn't XML) this won't work.
You have to find a way of getting the output from executing xml.php into parse.php.
The easy way to do this would be to change all your echo calls into $xml .= calls, and simply include xml.php into parse.php.
// xml.php
$xml = '';
$xml .= "<!DOCTYPE..."; //xml stuff here
$output .= "<title>" . $dataFromMySQL . "</title>";
// parse.php
include('xml.php');
simplexml_load_string($xml);
Note that your problem here shows the foolishness of using the error suppression operator #. If you hadn't used it, PHP would have shown you various errors which would have helped you to realise what the problem was.
Addendum: it occurs to me that the best way actually is to forget about the pointless XML step along the way and just convert the database output into HTML.
If you want to do this without rewriting xml.php, you can get PHP to process the file by accessing via url:
$doc = file_get_contents("http://localhost/xml.php");
You're literally loading the local file. Unless you evaluate it, the code doesn't run, so you'll just get the code itself.
You could use CURL to download xml.php over HTTP, or you could make the XML-generation component of the xml.php a callable function which you simply include and execute.
parse.php:
<?php
include('xml.inc');
$doc = #simplexml_load_string(xml_function()) or die("Error");
echo $doc->title;
xml.php:
<?php
include('xml.inc');
header("Content-type: text/xml");
echo xml_function();
xml.inc:
<?php
function xml_function() {
$dbc = mysql... //gets data from database
$xml = "<!DOCTYPE..."; //xml stuff here
$xml .= "<title>" . $dataFromMySQL . "</title>";
return $xml;
}
But... even that seems silly, honestly, when you could have both output methods connect to the same data and skip a generation/parse step. Simply output HTML/XML conditionally.
I have created a XML file using PHP's simple XML, saved the file. When opening the file in php using fopen and printing the contents. my XML looks like this: (see below)
<?xml version="1.0" encoding="UTF-8"?>
<home><orderList><delivery_cost>0.00</delivery_cost><delivery_surname>TEST</delivery_surname><delivery_postcode>1234</delivery_postcode><status>1</status></orderList></home>
I want the xml file looking all indented and on new lines for each element. Does anybody know how to do this?
Thanks
You can do this using the formatOutput property of DOMDocument.
Save your XML like this instead, presuming your XML is in a variable called $yourXML, and you want to save it to a file at $xmlFilePath:
$dom = new DOMDocument();
$dom->loadXML($yourXML);
$dom->formatOutput = true;
$formattedXML = $dom->saveXML();
$fp = fopen($xmlFilePath,'w+');
fwrite($fp, $formattedXML);
fclose($fp);
Code adapted from here.
This is called "pretty printing" and SimpleXML does not do that. If you search on Stack Overflow and elsewhere on the web you'll find custom solutions that do that.
Pretty printing is good for visulation but I don't recommend saving documents in that format.
If you're still looking for a pretty-printer, you can try SimpleDOM's asPrettyXML()
include 'SimpleDOM.php';
$home = simpledom_load_string('<?xml version="1.0" encoding="UTF-8"?>
<home><orderList><delivery_cost>0.00</delivery_cost><delivery_surname>TEST</delivery_surname><delivery_postcode>1234</delivery_postcode><status>1</status></orderList></home>');
echo $home->asPrettyXML();
echo "\n"; for new line in xml
ob_start(); echo '
' . "\n";?>
I am trying to find out how this would work
For testing purposes, I have made two websites.
One is calling a REST service from the other
I pull the xml data with file_get_contents
if I echo it, I can see a string off data.
But how can I use simpelxml on it, extract data from the nodes themselves?
If I use simplexml_load_file($url), I get some error saying xml declaration only allowed
at the start off the document?
I have this in my testfile
<?php
$url='http://www.woonbel.nl/gps/setgpsloc';
//not working
$xml =simplexml_load_file($url);
print_r($xml);
//just a string
$xml=file_get_contents($url);
echo "<h3>$xml</h3><br>";
?>
this was the xml I send.
I send this from a class file that I included in the top off my php file
if I am sure the webservice is called, maybe that has someting to do with the declaration error?
header('Content-type: text/xml');
echo "<?xml version=\"1.0\"?>\n";
echo "<response>\n";
echo "\t<status>$status_code</status>\n";
echo "\t<fout>Geen</fout>\n";
echo "</response>";
Thanks, Richard
Sounds like there is a blank line at the top of the file, when it should start with the xml declaration. For example:
<?xml version="1.0" encoding="utf-8"?>
Have you got empty lines before the declaration?
Your REST service should be returning XML contents, something like this:
<?xml version="1.0" encoding="utf-8"?>
<results>
<result>
<value awesome="true">LOLCATS</value>
</result>
</results>
You'd then do something along these lines to consume that REST service on the other site:
$xml = simplexml_load_string(file_get_contents('http://example.com/rest.xml'));
foreach($xml->result as $result) {
$value = $result->value;
$awesome = $result->attributes()->awesome;
// do something here with our values and attributes
}
The PHP docs for SimpleXML contain more complicated/real-world examples.
For your specific XML:
$xml = simplexml_load_string(file_get_contents('http://example.com/rest.xml'));
$status = $xml->status;
$fout = $xml->fout;
The error message clearly states that there is a blank, line or character, at the beginning of the xml-data. That could be file-encoding -issue.