0

如果我尝试通过 simplexml 向元素添加两次相同的属性,则会收到以下错误:

Warning: SimpleXMLElement::addAttribute() [function.SimpleXMLElement-addAttribute]: Attribute already exists...

作为一种解决方法,我将 if-else 语句用于三种可能性:

if ($a && $b) {
    $node -> addAttribute("class", "a b");
 }
 else if($a) {
    $node -> addAttribute("class", "a");
 }
 else if ($b) {
    $node -> addAttribute("class", "b");
 }

但这感觉有点笨拙,而且不是很可扩展。有没有人在使用更好的方法?

4

1 回答 1

2

而不是使用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)

希望这可以帮助 :-)

于 2009-09-15T04:32:54.537 回答