Airikr
Airikr

Reputation: 6436

Add multiple attributes to a child in SimpleXMLElement

I want to add multiple attributes to a child in SimpleXMLElement so it will look like this:

<data>
    <photo>
        <file size="3309519" size="JPG">P1270081</file>
    </photo>
</data>

As it is right now in my code, I can only add one attribute per child as the code below shows.

$xml = new SimpleXMLElement('<data/>');

$photo = $xml->addChild('photo');
$photo->addChild('file', 'P1270081')->addAttribute('size', '3309519');
$photo->addChild('uploaded', '2013-09-01 15:23:10')->addAttribute('by', 'edgren');

If I change the third line to $photo->addChild('file', 'P1270081')->addAttribute('size', '3309519')->addAttribute('type', 'JPG'); I'm getting this error message:

Fatal error: Call to a member function addAttribute() on a non-object in ...

I am new to creating XML files on the fly with SimpleXMLElement so I don't know how I shall fix this issue. What should I do to fix it?

Upvotes: 1

Views: 2554

Answers (2)

d.raev
d.raev

Reputation: 9546

$photo->addChild(..) // returns the created XML component .. and you can chain a action(one) directly one it.
But addAttribute(..) returns nothing .. so you get an error if you try to chain event after it.

$photo = $xml->addChild('photo');
$photo->addChild('file', 'P1270081')->addAttribute('size', '3309519');
$theNewChild = $photo->addChild('uploaded', '2013-09-01 15:23:10')

$theNewChild ->addAttribute('by', 'edgren');
$theNewChild ->addAttribute('type', 'JPG');

Upvotes: 0

Jimmy T.
Jimmy T.

Reputation: 4190

addAttribute returns void. If you want to add more attributes you have to something like this:

$file = $photo->addChild('file', 'P1270081');
$file->addAttribute('size', '3309519');
$file->addAttribute('type', 'JPG');

Upvotes: 4

Related Questions