Read XML file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikeman
Forum Newbie
Posts: 18
Joined: Wed Apr 07, 2010 7:18 am

Read XML file

Post 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.
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: Read XML file

Post by greyhoundcode »

What have you tried so far?
mikeman
Forum Newbie
Posts: 18
Joined: Wed Apr 07, 2010 7:18 am

Re: Read XML file

Post 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:

Code: Select all

#text =
news = 
Any ideas?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Read XML file

Post 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";
}
mikeman
Forum Newbie
Posts: 18
Joined: Wed Apr 07, 2010 7:18 am

Re: Read XML file

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Read XML file

Post 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".
Post Reply