Monday, 3 November 2014

PHP XML handling

songs.xml

<songs>
    <song dateplayed="2011-07-24 19:40:26">
        <title>I left my heart on Europa</title>
        <artist>Ship of Nomads</artist>
    </song>
    <song dateplayed="2011-07-24 19:27:42">
        <title>Oh Ganymede</title>
        <artist>Beefachanga</artist>
    </song>
    <song dateplayed="2011-07-24 19:23:50">
        <title>Kallichore</title>
        <artist>Jewitt K. Sheppard</artist>
    </song>
</songs>
eg

<?php
    $mysongs = simplexml_load_file('songs.xml');
    echo "<ul id="songlist">n";
    foreach ($mysongs as $songinfo):
        $title=$songinfo->title;
        $artist=$songinfo->artist;
        $date=$songinfo['dateplayed'];
        echo "<li><div class="title">",$title,"</div><div class="artist">by ",$artist,"</div><time>",$date,"</time></li>n";
    endforeach;
    echo "</ul>";
?>


<?php

$xmlData =<<< END

<?xml version="1.0"?>

<datas>

  <books>

    <book>

      <id>1</id>

      <title>PHP XML EXAMPLES</title>    

      <author>SUDHIR PANDEY</author>

    </book>

  </books>

</datas>

END;

$xml = simplexml_load_string($xmlData)

       or die("Error: Can not create object");

?>

simplexml_load_string() : Interprets a string of XML into an object

<?php
$xml = simplexml_load_file("books.xml")
       or die("Error: Cannot create object");
foreach($xml->children() as $books){

    foreach($books->children() as $book => $data){

      echo $data->id;

      echo $data->title;

      echo $data->author;

      echo "<br />";

    }

}
?>

children() — Finds children of given node
<?php
$xml = simplexml_load_file("books.xml")
       or die("Error: Cannot create object");
function processXML($node){

  foreach($node->children() as $books => $data){

    if(trim($data) != ""){

      echo $books.": ".$data;

      echo "<br />";

    }

    processXML($data);

  }

}

processXML($xml);

?>

Create XML
<?php
$xml = new DOMDocument("1.0");
$root = $xml->createElement("data");
$xml->appendChild($root);
$id   = $xml->createElement("id");
$idText = $xml->createTextNode('1');
$id->appendChild($idText);
$title   = $xml->createElement("title");
$titleText = $xml->createTextNode('"PHP Undercover"');
$title->appendChild($titleText);
$book = $xml->createElement("book");
$book->appendChild($id);
$book->appendChild($title);
$root->appendChild($book);
$xml->formatOutput = true;
echo "<xmp>". $xml->saveXML() ."</xmp>";
$xml->save("mybooks.xml") or die("Error");
?>

0 comments:

Post a Comment