Php 如何更改simpleXML元素的属性值?
我用SimepleXML解析了一个XML文件:Php 如何更改simpleXML元素的属性值?,php,xml,simplexml,Php,Xml,Simplexml,我用SimepleXML解析了一个XML文件: <element data="abc,def"> EL </element> 埃尔 但是现在我想在“data”属性中添加一些内容。不是在文件中,而是在我的变量中(在我从simplexml_load_文件获得的对象结构中) 我如何才能做到这一点?未经测试,但应该可以: $element->attributes()->data = ((string) $element->attributes()->
<element data="abc,def">
EL
</element>
埃尔
但是现在我想在“data”属性中添加一些内容。不是在文件中,而是在我的变量中(在我从simplexml_load_文件获得的对象结构中)
我如何才能做到这一点?未经测试,但应该可以:
$element->attributes()->data = ((string) $element->attributes()->data) . ',ghi';
嗯,它可以像
$element['data'].=',ghi'那样完成代码>您可以使用此函数(如果没有名称空间):
请使用更正后的
class ExSimpleXMLElement extends SimpleXMLElement
{
function setAttribute(ExSimpleXMLElement $node, $attributeName, $attributeValue, $replace=true)
{
$attributes = $node->attributes();
if (isset($attributes[$attributeName])) {
if(!empty($attributeValue)){
if($replace){
$attributes->$attributeName = (string)$attributeValue;
} else {
$attributes->$attributeName = (string)$attributes->$attributeName.(string)$attributeValue;
}
} else {
unset($attributes->$attributeName);
}
} else {
$node->addAttribute($attributeName, $attributeValue);
}
}
}
例如:
<?php
$xml_string = <<<XML
<root>
<item id="foo"/>
</root>
XML;
$xml1 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
$xml1->setAttribute($xml1, 'id', 'bar');
echo $xml1->asXML();
$xml2 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
$xml2->setAttribute($xml2->item, 'id', 'bar');
echo $xml2->asXML();
$xml3 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
$xml3->setAttribute($xml3->item, 'id', 'bar', false);
echo $xml3->asXML();
$xml4 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
$xml4->setAttribute($xml4->item, 'id', NULL);
echo $xml4->asXML();
?>
项目“id”、“bar”);
echo$xml2->asXML();
$xml3=simplexml_load_string($xml_string,'exsimplexmlement');
$xml3->setAttribute($xml3->item'id',bar',false);
echo$xml3->asXML();
$xml4=simplexml_load_string($xml_string,'exsimplexmlement');
$xml4->setAttribute($xml4->item'id',NULL);
echo$xml4->asXML();
?>
结果:
<?xml version="1.0"?>
<root id="bar">
<item id="foo"/>
</root>
<?xml version="1.0"?>
<root>
<item id="bar"/>
</root>
<?xml version="1.0"?>
<root>
<item id="foobar"/>
</root>
<?xml version="1.0"?>
<root>
<item/>
</root>
<?xml version="1.0"?>
<root id="bar">
<item id="foo"/>
</root>
<?xml version="1.0"?>
<root>
<item id="bar"/>
</root>
<?xml version="1.0"?>
<root>
<item id="foobar"/>
</root>
<?xml version="1.0"?>
<root>
<item/>
</root>