Page 1 of 1
Read XML file
Posted: Fri Jul 30, 2010 10:10 am
by mikeman
I have an xml as follows:
Code: Select all
<ticker interval="50" direction="-1">
<news headline="01 August - Launch site" link="/news.php" target="_self" />
</ticker>
What php code would I use to read this file? I tried a few differnet options but they threw up errors. I wondered if it was beacuse this particular xml doesn't have normal closing tag ie: </news> - it just has /> I cannot change the xml as it is linked in with a flash news ticker on the site.
Cheers.
Re: Read XML file
Posted: Fri Jul 30, 2010 1:18 pm
by greyhoundcode
What have you tried so far?
Re: Read XML file
Posted: Mon Aug 02, 2010 3:44 am
by mikeman
Ok the first error was that my full xml had an & character in it. After removing that I amended the code and I now get these results:
Code: Select all
$xmlDoc = new DOMDocument();
$xmlDoc->load("../../data.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes as $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
I get the following output:
Any ideas?
Re: Read XML file
Posted: Mon Aug 02, 2010 4:02 am
by requinix
SimpleXML is so much easier to deal with than DOMDocument - as far as XML is concerned.
Code: Select all
$xml = <<<XML
<ticker interval="50" direction="-1">
<news headline="01 August - Launch site" link="/news.php" target="_self" />
</ticker>
XML;
$xml = new SimpleXMLElement($xml);
foreach ($xml->news as $newsitem) {
echo $newsitem["headline"], " (", $newsitem["link"], ")\n";
}
Re: Read XML file
Posted: Mon Aug 02, 2010 4:19 am
by mikeman
Thanks tasairis that code looks useful. I will create a form to amend the xml but how do I go about writing back to the xml file?
Re: Read XML file
Posted: Mon Aug 02, 2010 4:59 am
by requinix
There's
->asXML, but note that it may reformat your XML in a way you don't like - it's still totally correct, just not necessarily "pretty".