在 PHP 中动态编辑 XML


Dynamically editing XML in PHP

我正在尝试读取和写入始终不同的XML文件。

我想做的是定义CSS属性,这些属性可以为我的css中的每个类/id更改(由php完成)。

所以一个元素可能看起来像这样:

<element id="header">
    <position>left</position>
    <background>#fff</background>
    <color>#000</color>
    <border>2px dotted #GGG</border>
</element>

但是内部节点可以更改(任何 css 属性)。

我想阅读此内容,然后制作一个可以编辑属性的表单(设法执行此操作)。

现在我需要保存 XML。由于PHP,我无法一次提交完整的表单(无法提交您不知道表单元素名称的表单)。我正在尝试使用 Ajax 执行此操作,并在表单中编辑时保存每个节点。(更改时)

所以我知道元素的"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();

看到它工作