如何在运行时为数组索引提供命名键

时间:2015-05-29 13:34:26

标签: php mysql arrays xml xml-serialization

这里我试图使用XMLSerializer类将数据从mysql表转换为xml文件。我希望xml文件是这样的

enter image description here

为此,我需要将数字索引更改为'book'。目前我可以生成以下形式的数组:它具有数字索引,但出于我的目的,两个索引(0和1)必须是'书'。

enter image description here

如何将两个数字索引更改为“book”??

完整代码:

   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());
   }

1 个答案:

答案 0 :(得分:2)

您需要在default tag中设置XML_Serializer

所以你的代码应该是:

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

$serializer = new XML_Serializer($options);

点击此链接了解详情:https://pear.php.net/manual/en/package.xml.xml-serializer.xml-serializer.examples.php