Search code examples
phpxmlsimplexml

Updating a xml file with php simplexml tool


I have a very simple xml content videolar.xml. Flash player takes these elements and plays them. I want to change the <title> and <youtube> elements by php simplexml. I wrote a code video.php to change these elements. When I run video.php it prints like below. It looks like it works, but if I play the player it plays led zeppelin still, and does not play whitesnake. If I open video.xml by browser I see that xml file has not changed. Still led zeppelin. So how can I update flashplayer's playlist?

videolar.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <playlist>
    <track>
      <title>led zeppelin - kashmir</title>
      <youtube>sfR_HWMzgyc</youtube>
    </track>
    <track>
      <title>pink floyd - eclipse</title>
      <youtube>BUwUKyztI10</youtube>
    </track>
  </playlist>

video.php

<?php
  $completeurl = $_SERVER['DOCUMENT_ROOT'].'/ytplayer/videolar.xml';
  $xml = simplexml_load_file($completeurl);

  $xml->track[0]->title = 'Whitesnake - Is this love';
  $xml->track[0]->youtube = 'GOJk0HW_hJw';

  print_r($xml);
?>

When I run this code above it prints:

(
  [track] => Array
  (
    [0] => SimpleXMLElement Object
    (
      [title] => Whitesnake - Is this love
      [youtube] => GOJk0HW_hJw
    )
    [1] => SimpleXMLElement Object
    (
      [title] => pink floyd - eclipse
      [youtube] => BUwUKyztI10
    )
  )  
)

Solution

  • You need to save modified xml back into file

    <?php
        $completeurl = $_SERVER['DOCUMENT_ROOT'].'/ytplayer/videolar.xml';
        $xml = simplexml_load_file($completeurl);
    
        $xml->track[0]->title = 'Whitesnake - Is this love';
        $xml->track[0]->youtube = 'GOJk0HW_hJw';
    
        $xml->asXML($completeurl)
    ?>