0

How can I create more than one attribute for a DOM Element?

Here I have one attribute

$data = $xml->createElement('enclosure', $rssdata["nNr"]);
$enclosure = $xml->createAttribute('type');
$enclosure->value = 'image/jpeg';
$data->appendChild($enclosure);
$item->appendChild($data);

But I need two attributes like the export here for URL

<enclosure type="image/jpeg" url="">1</enclosure>
0

3 Answers 3

3

With PHP's DOM extension, you can more easily add one or more attributes to a DOMElement by using the DOMElement::setAttribute method.

Saying that $enclosure is the DOMElement for the <enclosure> element in your question:

$enclosure->setAttribute("type", "image/jpeg");
$enclosure->setAttribute("url", "");

Just adds those two attributes you're asking for. You can do one, two or N attributes that way.

Background Info: In XML an element can only have one attribute with the same name.

Sign up to request clarification or add additional context in comments.

Comments

1

Just add three more lines:

$data = $xml->createElement('enclosure', $rssdata["nNr"]);

$enclosure = $xml->createAttribute('type'); # creating attribute 1
$enclosure->value = 'image/jpeg';           # setting value
$data->appendChild($enclosure);             # adding attribute to element

$url = $xml->createAttribute('url');  # creating attribute 2
$url->value = '';                     # setting value
$data->appendChild($url);             # adding attribute to element

$item->appendChild($data);

If you have many attributes to add, you might consider creating a function to reduce code duplication.

Your variable names may be confusing. If you rename $enclosure and $data your code might become clearer and easier to read:

$enclosureElement = $xml->createElement('enclosure', $rssdata["nNr"]);

$typeAttribute = $xml->createAttribute('type'); # creating attribute 1
$typeAttribute->value = 'image/jpeg';           # setting value
$enclosureElement->appendChild($typeAttribute); # adding attribute to element

$urlAttribute = $xml->createAttribute('url');  # creating attribute 2
$urlAttribute->value = '';                     # setting value
$enclosureElement->appendChild($urlAttribute); # adding attribute to element

$item->appendChild($enclosureElement);

1 Comment

With ->createAttribute() you can set the value as well - just add it as 2nd argument. Even easier: Use setAttribute(). No need to create one.
1

Just add another one the way you added the first one.

$urlAttr = $xml->createAttribute('url');
...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.