[英]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.