PHP DOMDocument添加子xml feed

时间:2022-10-20 18:36:22

If want xml to do this:

如果想要xml这样做:

    <itunes:owner>
        <itunes:name>Name</itunes:name>
        <itunes:email>email</itunes:email>
    </itunes:owner>

This code does not work. the name and email is not between owner tags.

此代码不起作用。名称和电子邮件不在所有者标记之间。

instead it is doing this:

相反它是这样做的:

    <itunes:owner> </itunes:owner>
    <itunes:name>Name</itunes:name>
    <itunes:email>email</itunes:email>

This PHP code does not work. the name and email is not between owner tags.

这个PHP代码不起作用。名称和电子邮件不在所有者标记之间。

$xml = new DOMDocument("1.0","UTF-8");
 ...
    $chan->appendChild($xml->createElement('itunes:owner', 'ame'));
    $chanow = $chan->appendChild($xml->createElement('itunes:name', 'Name'));
    $chanow = $chan->appendChild($xml->createElement('itunes:email', 'email'));

So how do I add the child element?

那么我该如何添加子元素呢?

Sorry this is my first experience with DOMDocument.

对不起,这是我第一次使用DOMDocument。

1 个解决方案

#1


0  

You're trying to append a Child to the wrong parent.

您正试图将一个Child附加到错误的父级。

$chan->appendChild($xml->createElement('itunes:owner', 'ame'));

Try this:

$xml->formatOutput = true; //better readability

$chan = $xml->appendChild($xml->createElement('itunes:owner'));
$chanow = $chan->appendChild($xml->createElement('itunes:name', 'Name'));
$chanow = $chan->appendChild($xml->createElement('itunes:email', 'email'));

echo $xml->saveXML(); //displaying the output

This should produce the following output:

这应该产生以下输出:

<itunes:owner>
  <itunes:name>Name</itunes:name>
  <itunes:email>email</itunes:email>
</itunes:owner>

Demo!

#1


0  

You're trying to append a Child to the wrong parent.

您正试图将一个Child附加到错误的父级。

$chan->appendChild($xml->createElement('itunes:owner', 'ame'));

Try this:

$xml->formatOutput = true; //better readability

$chan = $xml->appendChild($xml->createElement('itunes:owner'));
$chanow = $chan->appendChild($xml->createElement('itunes:name', 'Name'));
$chanow = $chan->appendChild($xml->createElement('itunes:email', 'email'));

echo $xml->saveXML(); //displaying the output

This should produce the following output:

这应该产生以下输出:

<itunes:owner>
  <itunes:name>Name</itunes:name>
  <itunes:email>email</itunes:email>
</itunes:owner>

Demo!