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);
给出:
<?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>
所以,我想添加/更改以下内容:
- 更改 XML 版本行以包含编码(刮掉这个,我发现 --> $xml = new DOMDocument( '1.0', 'UTF-8');)
- 向元素添加附加信息。例如 [item] 到 [item item-id="abcd"]
- 还有 [quantity] 到 [quantity]0[/quantity]
有人可以帮我吗?蒂亚!
$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:
- change the XML version line to include encoding (scrape this, I figured out --> $xml = new DOMDocument('1.0', 'UTF-8');)
- Add additional information to an element. e.g. [item] to [item item-id="abcd"]
- Also [quantity] to [quantity]0[/quantity]
Can someone help me with this? TIA!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经很接近了。
2: 设置属性:
3: 添加标签/元素时添加数据:
2+: 使用 HTMLSpecialchars 防止浏览器隐藏标签:
You're already pretty close.
2: set an attribute:
3: add data while adding a tag/element:
2+: Use HTMLSpecialchars to prevent the browser to hide the tags: