[英]Dynamically editing XML in PHP
我正在尝试读取和写入始终不同的 XML 文件。
我想要做的是定义可以为我的 css 中的每个类/id 更改的 CSS 属性(由 php 完成)。
所以一个元素可能看起来像这样:
<element id="header">
<position>left</position>
<background>#fff</background>
<color>#000</color>
<border>2px dotted #GGG</border>
</element>
但是内部节点可能会改变(任何 css 属性)。
我想阅读这篇文章,然后制作一个表格,我可以在其中编辑属性(设法做到这一点)。
现在我需要保存 XML。 由于 PHP,我无法一次提交完整的表单(无法提交您不知道表单元素名称的表单)。 我正在尝试使用 Ajax 来完成它并在表单中编辑时保存每个节点。 (onChange)
所以我知道元素的“id”标签和节点名称。 但是我找不到直接访问节点并使用 DOMDocument 或 SimpleXML 对其进行编辑的方法。
有人告诉我尝试 XPath,但我无法使用 XPath 进行编辑。
我怎么能尝试这样做呢?
$xml = <<<XML
<rootNode>
<element id="header">
<position>left</position>
<background>#fff</background>
<color>#000</color>
<border>2px dotted #GGG</border>
</element>
</rootNode>
XML;
// Create a DOM document from the XML string
$dom = new DOMDocument('1.0');
$dom->loadXML($xml);
// Create an XPath object for this document
$xpath = new DOMXPath($dom);
// Set the id attribute to be an ID so we can use getElementById()
// I'm assuming it's likely you will want to make more than one change at once
// If not, you might as well just XPath for the specific element you are modifying
foreach ($xpath->query('//*[@id]') as $element) {
$element->setIdAttribute('id', TRUE);
}
// The ID of the element the CSS property belongs to
$id = 'header';
// The name of the CSS property being modified
$propName = 'position';
// The new value for the property
$newVal = 'right';
// Do the modification
$dom->getElementById($id)
->getElementsByTagName($propName)
->item(0)
->nodeValue = $newVal;
// Convert back to XML
$xml = $dom->saveXML();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.