如何使用PHP显示XML子元素

时间:2018-01-31 07:26:37

标签: php xml

以下是我想用php显示的示例XML:

<message>
    <subject>Welcome <name>Username</name></subject>

    <paragraph_1>
    Hello <name>Username</name>. Thank for joining us.
    </paragraph_1>
</message>

这是我的php代码,用于显示xml。

$xml = simplexml_load_file("xml/welcome_message.xml") or die("Error: Cannot create object");

$your_name = "John";
// update name
$xml->subject->name = $your_name;
$xml->paragraph_1->name = $your_name;

$line_1 = "<p>". $xml->subject ."</p>";
$line_2 = "<p>". $xml->paragraph_1 ."</p>";

echo $line_1 .  $line_2;

我遇到的问题是上面的代码只显示没有name元素的消息,如下所示:

Welcome 

Hello . Thank for joining us.

如何让它显示如下的名称元素:

 Welcome John

Hello John . Thank for joining us.

2 个答案:

答案 0 :(得分:2)

您可以使用DOMDocument以更灵活的方式更改数据。

也许尝试这样的事情:

$your_name = "John";

$doc = new DOMDocument();
$doc->load('xml/welcome_message.xml');
$elements = $doc->getElementsByTagName("name") ;
foreach ($elements as $element) {
    $element->textContent = $your_name ;
}

// Output
$subject = $doc->getElementsByTagName('subject') ;
$paragraph_1 = $doc->getElementsByTagName('paragraph_1') ;
$line_1 = "<p>". $subject->item(0)->textContent ."</p>";
$line_2 = "<p>". $paragraph_1->item(0)->textContent ."</p>";

echo $line_1 .  $line_2; // <p>Welcome John</p><p>Hello John. Thank for joining us.</p>

答案 1 :(得分:0)

工作正常

  $your_name = "John";
    $xml->message->subject->name = $your_name;
    $xml->message->paragraph_1->name = $your_name;
    $line_1 = "<p>". $xml->subject.$xml->message->subject->name."</p>";
    $line_2 = "<p>". $xml->paragraph_1 .$xml->message->paragraph_1->name."</p>";

    echo $line_1 .  $line_2;