PHP DOM:在XML数据中填充值

时间:2011-07-06 18:23:23

标签: php xml dom populate

$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);

给出:

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

因此,我设法使用DOM在PHP中创建上述内容。我一直在网上搜索如何“填充”,但我找不到任何有关如何执行此操作的信息。

更具体地说,我希望这看起来像这样

<?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>

所以,我想添加/更改以下内容:

  1. 更改XML版本行以包含编码(刮掉这个,我想出来了 - &gt; $ xml =新的DOMDocument('1.0','UTF-8');)
  2. 向元素添加其他信息。例如[item]至[item item-id =“abcd”]
  3. [数量]至[数量] 0 [/数量]
  4. 有人可以帮我吗? TIA!

1 个答案:

答案 0 :(得分:1)

你已经非常接近了。

2:设置属性:

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

3:添加标签/元素时添加数据:

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

2+:使用HTMLSpecialchars阻止浏览器隐藏标记:

echo nl2br(html_specialchars($xml->saveXML(), ENT_QUOTES));