dongnong7524 2011-07-06 18:23
浏览 54
已采纳

PHP DOM:在XML数据中填充值

$xml = new DOMDocument();
$xml_store_inventory = $xml->createElement('store-inventory');  // highest layer
$xml_item = $xml->createElement('item');
$xml_quantity = $xml->createElement('quantity');

$xml->appendChild($xml_store_inventory);
$xml_store_inventory->appendChild($xml_item);
$xml_location->appendChild($xml_quantity);

gives:

<?xml version="1.0"?>
<store-inventory>
  <item>
      <quantity></quantity>
  </item>
</store-inventory>

So, I managed to create the above in PHP using DOM. I've been searching online on how to "populate," but I'm not finding any information on how to do this.

More specifically, I'd like this to look like this

<?xml version="1.0" encoding="UTF-8"?>
<store-inventory
xmlns="http://..."
xmlns:xsi="http://..."
xsi:schemaLocation="http://...">

    <item item-id="abcd">
       <quantity>0</quantity>
    </item>
</store-inventory>

So, I'd like to add/change the following:

  1. change the XML version line to include encoding (scrape this, I figured out --> $xml = new DOMDocument('1.0', 'UTF-8');)
  2. Add additional information to an element. e.g. [item] to [item item-id="abcd"]
  3. Also [quantity] to [quantity]0[/quantity]

Can someone help me with this? TIA!

  • 写回答

1条回答 默认 最新

  • dsa89029 2011-07-06 18:44
    关注

    You're already pretty close.

    2: set an attribute:

    // set/add an attribute:
    $xml_item->setAttribute('item-id', "abcd");
    

    3: add data while adding a tag/element:

    // add an element with data:
    $xml_quantity = $xml->createElement('quantity', '0');
    

    2+: Use HTMLSpecialchars to prevent the browser to hide the tags:

    echo nl2br(html_specialchars($xml->saveXML(), ENT_QUOTES));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果