而不是使用SimpleXMLElement::addAttribute
,也许你可以只使用数组访问参数?
例如,考虑到您有那部分代码:
$str = <<<XML
<root>
<elem>glop</elem>
</root>
XML;
$xml = simplexml_load_string($str);
var_dump($xml->elem);
这给出了这个输出:
object(SimpleXMLElement)[2]
string 'glop' (length=4)
您可以通过这种方式添加“class=a”属性:
$xml->elem['class'] .= 'a ';
var_dump($xml->elem);
这会给你这个输出:
object(SimpleXMLElement)[5]
public '@attributes' =>
array
'class' => string 'a ' (length=2)
string 'glop' (length=4)
然后,通过将该值连接到类的现有值来添加“class=b”属性,这样:
$xml->elem['class'] .= 'b ';
var_dump($xml->elem);
你得到:
object(SimpleXMLElement)[7]
public '@attributes' =>
array
'class' => string 'a b ' (length=4)
string 'glop' (length=4)
注意属性值末尾的空格;也许你会想清理这个,使用 trim :
$xml->elem['class'] = trim($xml->elem['class']);
var_dump($xml->elem);
瞧:
object(SimpleXMLElement)[8]
public '@attributes' =>
array
'class' => string 'a b' (length=3)
string 'glop' (length=4)
希望这可以帮助 :-)