简体   繁体   中英

How to display XML child elements with PHP

Here is my sample XML which I want to display using php:

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

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

And here is my php code to display the 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;

The problem I facing is that the above code only displays the message without name element as below:

Welcome 

Hello . Thank for joining us.

How can I make it display name element like below:

 Welcome John

Hello John . Thank for joining us.

You could use DOMDocument to change your data in a more flexible maner.

Maybe try something like this :

$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>

it is work fine

  $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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM