dongtidai6519 2009-07-06 14:59
浏览 76
已采纳

使用PHP DOM将PostgreSQL查询的结果转换为XML

Given SQL as an input, I have to query a PostgreSQL database and return the results as XML. I have done this with the following code:

<?php

$link = "host=localhost dbname=company user=pgsql password=password";
$connect = pg_connect($link);

$query = "SELECT *  FROM customer";
$result = pg_query($connect, $query);

$doc = new DomDocument("1.0");

$root = $doc->createElement('data');
$root = $doc->appendChild($root);

while($row = pg_fetch_assoc($result)){
    $node = $doc->createElement('collection');
    $node = $root->appendChild($node);

    foreach($row as $fieldname => $fieldvalue){
       $node->appendChild($doc->createElement($fieldname, $fieldvalue));
    }
}

$doc->save("cust.xml");

?>

Eventually, I will be applying a CSS stylesheet directly to the XML document. I will specify style information for each 'collection' node. However, it is possible that there will be sub-collections of collections, and even sub-sub-collections and so on.

(So: Master, detail, sub-detail, sub-sub-detail, etc.)

The problem is, my code will only generate XML for Master, detail, sub-detail. How can I modify my code so that the XML generated will always "capture" all of the levels of the data?

Thanks...


Yes, I'm referring to a hierarchical relationship. For example, with my current code, I can see all of the attributes, of fields, of the "Customer" table. However, what if one of the customer attributes were 'Address', and the Customer had multiple addresses? This would need to appear as...

 <data> 
   <collection> 
     <fname>Joe</fname> 
     <lname>Smith</lname> 
     <address> 
       <address A> 123...</address A> 
       <address B> 234...</address B> 
   </collection>
 </data>

I'm trying to modify my code to "pick up" on the fact that address, although an attribute, has sub-attributes...

  • 写回答

1条回答 默认 最新

  • dongmozhui3805 2009-07-06 15:10
    关注

    First, you may consider performing your xml mapping within Postgres itself using the available built-in functions. Two benefits of this are that your data abstraction functionality stays together and that Postgres is much better optimized to perform this task efficiently than php is. If you have to do any higher level modification of the xml, xslt should do the trick.

    As for the problem you mention, I'm not sure if you're referring to the data in the table having a hierarchical relationship?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?