SimpleXmlElement-> addAttribute()不允许空字符串

Description:

A call like addAttribute("attrname", "") results in "PHP Warning: SimpleXMLElement::addAttribute(): Attribute name and value are required". In addition to the warning, the attribute is discarded.

Reproduce code:

<?php
$xml = new SimpleXmlElement("<img></img>");
$xml->addAttribute("src", "foo");
$xml->addAttribute("alt", "");
echo $xml->asXML()."
";
?>

Expected result:

<?xml version="1.0"?>
<img src="foo" alt=""/>

Actual result:

PHP Warning:  SimpleXMLElement::addAttribute(): Attribute name and value are required in [...]/test.php on line 4
<?xml version="1.0"?>
<img src="foo"/>

this problem exists in PHP 5.2.1, but in PHP5.3.5 it works as I expect, but I can't change my php version(for some reason). Is there any way to solve this?

can you try by changing below line

$xml = new SimpleXmlElement("<img>");

and also you can try with below also

    $xml = new DOMDocument('1.0', 'iso-8859-1');

    $doc = $xml->createElement('document');
    $doc = $xml->appendChild($doc);

The documentation for SimpleXMLElement::addAttribute says that the value parameter is optional, so you can try omitting that. I didn't try using php 5.2.1, but 5.2.6 and 5.3 both work with the code you posted, and both emit warnings if you leave out the value argument (which confuses me wrt the documentation).

Does this work for you? I don't have 5.2.1 at hand to test. It works on 5.3.6 though.

$xml = simplexml_load_string('<img src="images/bg.png" alt="" />');
echo $xml->asXML();