Include a new XML child element using PHP

I've encountered an issue with my PHP code while trying to add multiple nodes from an XML file. Currently, the code only adds the first node, but I need it to include all child nodes under the name 'node'.

XML Structure:

<root>
<result>
<node>
<someting>asdasd</something>
</node>
<node>
<someting>asdasd</something>
</node>
  </result>
        <error/>
      </root>

Desired XML Output:

<root>
<result>
<node>
<someting>asdasd</something>
<Shipping_Cost>9</Shipping_Cost>
</node>
<node>
<someting>asdasd</something>
<Shipping_Cost>9</Shipping_Cost>
</node>
  </result>
        <error/>
      </root>

Current PHP Function:

function fn_add_shipping($xmlFileToLoad, $destination)
{
    $xmlFileToLoad = 'shipping.xml';
    $dom = new DOMDocument();
    $dom->load($xmlFileToLoad);
    $shipping = $dom->getElementsByTagName('node')->item(0);
    $ship = $dom->createElement('Shipping_Cost', '9');
    $shipping->appendChild($ship);
    $dom->save($destination);
    return $destination;
}

Answer №1

Apologies for the confusion earlier on your query. It seems I misunderstood the purpose of the 2nd XML file that you requested to be generated by the PHP method. Upon reviewing it now, I comprehended where the issue lies. You have only invoked the append function once. To resolve this, you should iterate through each node and call the append function before writing the results to the target XML file.

Consider implementing something along these lines:

function fn_create_shipping($sourceXmlFile, $destination)
{
    $sourceXmlFile = 'shipping.xml';
    $dom = new DOMDocument();
    $dom->load($sourceXmlFile);
    $shippingNodes = $dom->getElementsByTagName('node');
    
    for ($x=0; $x<$shippingNodes->length; $x++)
    {
        $newShippingNode = $dom->createElement('Shipping_Cost', '9');
        $shippingNodes[$x]->appendChild($newShippingNode);
    }
    
    $dom->save($destination);
    return $destination;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

What steps can I take to prevent inserting an href into a conflicting keyword within a string?

Reviewing the code snippet provided: $text = "Google has released a version specifically for smart devices running Android operating system from version '25' of its famous Chrome browser. Google has not updated the Chrome application for Android ...

PHP Dividing the outcome

Looking for PHP assistance, specifically with modifying hexadecimal values. I currently have a value of 612B in hex decimal format and need to switch the positions of 61 & 2B to become 2B61. $skillsearch1 = odbc_exec($conn1,"select cast(cast(rever ...

PHP MySQL outputting data in a dropdown menu format

Struggling to extract data from a database and display it as a dropdown list. I am fetching the foreign key, its unique code, and its name/title to be displayed in a dropdown list for input into a new table. $sql = "SELECT quali_code, title FROM ...

Sharing Data Between Pages in PHP Using Variables

I've been struggling with this issue for a while now and despite trying everything, I still can't seem to pass variables to a second page successfully. On the first page: <form method="post" name="form1" id="form1" enctype="multipart/form-da ...

PHP is experiencing issues when trying to insert data into the database

When I run a query in phpMyAdmin such as INSERT INTO table('نچجاعجان'); it appears correctly, but when I try to insert data through my PHP page, it displays in the field like this: ÙاننناÙنعن The col ...

How to retrieve the index of a specific value in a PHP array

In my code, I have two arrays named $fonts['google'] and $data['value']. Here is the content of each: When I use var_dump ($fonts['google']), it outputs: array(4) { [0]=> array(3) { ["family"]=> string(7) "ABeeZee" ...

Exploring the intricacies of XML embedded within JSON

Utilizing YQL for jQuery, I am able to successfully execute cross-domain REST requests. The JSON response contains the desired XML data as key-value pairs. The specific request being made is: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%2 ...

Capture and store components in Laravel using a method other than the primaryKey

I'm facing a challenge where I need to retrieve an element from the database but using the FIND method isn't working for me. This is because FIND only searches by the primaryKey, and what I require is not based on my primaryKey. Therefore, I appr ...

How can one import an external file containing additional TCPDF code into TCPDF?

I've been experimenting with creating a PDF that contains a lot of dynamic content. I want to include specific code based on an external file that I call: include 'external-file.php'; The contents of external-file.php are as follows: $pdf ...

Troubleshooting: Symfony Entity Failing to Save in Database during Persist Operation

This code functions properly when used in controllers, but it encounters issues when injected into a command. public function execute(InputInterface $input, OutputInterface $output) { $em = $this->getDoctrine()->getManager(); try { $t ...

Check if a key exists in an array that contains sub-arrays using the function array_key_exists

I am encountering an issue with a function. My goal is to include all pages, but the problem is that not all pages are named like the parameter $_GET['page']. For example, if I call index.php?p=accueil, it should redirect to php/home.php. Anoth ...

Using jQuery ajax and PHP to add information to a MySQL database

I've been puzzling over how to use jQuery's ajax() function to post form data from a textarea to a mysql database. The problem is, I'm struggling to grasp the underlying concept. Imagine there's a form: <form method="post" action=" ...

Guide to Embedding a SQL Table into an HTML Table

I need to set up a table within my current webpage to showcase a list of movies along with their genres. Welcome to my Movies page. The index.php file contains all the necessary database credentials and establishes the connection. <?php session_start( ...

What steps should I take to resolve the issue with the Error: spawn php-cgi ENOENT?

My current setup involves Nuxt with php-express, and I've been troubleshooting a persistent error in my php script for hours without success. *server.cjs : * const express = require("express"); const expressPhp = require("express-php&q ...

Steps to update the action attribute in a form element upon clicking a button

Within the following code snippet, there are 3 buttons - update, back, and delete. Depending on which button is clicked, the $page variable should be assigned to the action attribute in the form element, with the posted data being sent accordingly. <f ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

PHP error: Trying to access an undeclared variable after using the require function

Currently, I'm facing a challenge while creating a PHP site. The issue is that I am unable to utilize included variables in the included files! index.php <?php require 'core/init.php'; ?> init.php <?php require 'config.php& ...

Unable to Preview jQuery Video in Div After PHP Validation, But Image Preview Works Fine

Successfully utilizing the code below (with variations in IDs, etc.), I am able to preview a banner image in a div after PHP validates the upload using AJAX. This process is working perfectly without any issues. However, I am encountering an issue when at ...