Nick
Nick

Reputation: 9373

PHP access XML node element

I am trying to edit some XML with PHP. Currently the XML looking something like:

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel>
    <title>Main Title</title>
    <link>http://exmaple.com</link>
    <description> blahblahblah </description>
    <language>en</language>
    <item>
      <title>Tite1</title>
      <link>http://www.example.com (THIS IS WHAT I WANT)</link>
      <description>blah blah blah</description>
    </item>
    .
    .
    .
 </channel>
</rss>

I've tried to access the 2nd level link but my code only changes the first Link node value. Here is the code:

       $xml->load('http://www.google.com/doodles/doodles.xml');
    $element = $xml->getElementsByTagName('channel')->item(0);
    $secondlvl = $element->getElementsByTagName('item')->item(0);
    $2ndlevellinknode = $element->getElementsByTagName('link')->item(0);
    $2ndlevellinknode->nodeValue = $newvalue;

Any suggestions? Also is it possible to use this line of code in a for loop like this

for ($i = 0; $i <= 20; $i++) {
    $element = $xml->getElementsByTagName('channel')->item(0);
    $secondlvl = $element->getElementsByTagName('item')->item(0);
    $2ndlevellinknode = $element->getElementsByTagName('link')->item($i);
    $2ndlevellinknode->nodeValue = $newvalue;
}

Upvotes: 1

Views: 1108

Answers (1)

busypeoples
busypeoples

Reputation: 737

this should give you an idea.

$f = simplexml_load_file('test.xml');
print $f->channel->title . "\n";
print $f->channel->link . "\n";
print $f->channel->description . "\n";
foreach($f->channel->item as $item) {
  print $item->title . "\n";
}

Upvotes: 2

Related Questions