2

Here i am trying to use XMLSerializer class to convert data from mysql table into an xml file.I want the xml file to be like this

enter image description here

For this ,i need to change the numeric indexes into 'book'.Currently i can generate an array of the following form:It has numeric indexing ,but for my purpose both of the indexes (0 and 1) have to be 'book'.

enter image description here

How can i change both the numeric indexes to be 'book'??

FULL CODE:

   include('XMLSerializer/XML/Serializer.php');
   $host='localhost';
   $user='root';
   $pass='';
   $db='xmlserializer';

   $dbh=new PDO("mysql:host=$host;dbname=$db",$user,$pass);
   $sql='SELECT lname,fname FROM employee';
   $sth=$dbh->prepare($sql);
   $sth->execute();

   $xml=array('library'=>array());

   $i=0;
   while($result=$sth->fetch(PDO::FETCH_ASSOC)){
       array_push($xml['library'],$result);

   }
   print_r($xml);
   $serializer=new XML_Serializer();


   $result=$serializer->serialize($xml);
   if($result===true){
      file_put_contents('myxml.xml',$serializer->getSerializedData());
   }
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 2
    If your 2 keys become "book", they will be overriden... Do you wish keys like ["book1"], ["book2"] ? or you want one more dimension to be ["library"]["book"][0] ? – Random May 29 '15 at 13:37
  • i can manage what you suggested but to get the desired xml format both of them have to be book. – AL-zami May 29 '15 at 13:39
  • The problem is that you can't have an array like `array("book" => array(...), "book" => array(...))`, so you should better create separate arrays, one for each book, and then generate your xml for each array... – Random May 29 '15 at 13:45
  • i know they will override each onther.But still can't figure out an alternative way :( – AL-zami May 29 '15 at 13:49
  • As I said, you'll have to generate the xml of each book separately, or you have to change your hierarchy as @ericMartinez suggested... – Random May 29 '15 at 13:51

1 Answers1

2

You need to set default tag in you XML_Serializer:

So your code should be:

$options = array(
      "defaultTagName"  => "book",
);

$serializer = new XML_Serializer($options);

Check this link for more information : https://pear.php.net/manual/en/package.xml.xml-serializer.xml-serializer.examples.php

Hardik Solanki
  • 3,153
  • 1
  • 17
  • 28