我使用SimpleXML解析XML文件:
<element data="abc,def">
EL
</element>
但现在我想在“数据”属性上添加一些内容。不在文件中,而是在我的变量中(在我从simplexml_load_file获得的对象结构中)。
我怎样才能做到这一点?
未经测试,但应该工作:
$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();
?>
结果:
<?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>
您可以使用此函数(如果没有名称空间):
function setAttribute(SimpleXMLElement $node, $attributeName, $attributeValue)
{
$attributes = $node->attributes();
if (isset($attributes->$attributeName)) {
$attributes->$attributeName = $attributeValue;
} else {
$attributes->addAttribute($attributeName, $attributeValue);
}
}