What is the best way to directly access a child node for updating or removing?

This is an example of an xml file structure:

<participants>
  <participant>
    <number>1</number>
    <name>toto</name>
  </participant>
  <participant>
    <number>2</number>
    <name>titi</titi>
  </participant>
  <participant>
    <number>3</number>
    <name>tata</titi>
  </participant>
</participants>

The goal is to directly access a specific node in the XML by using the participant number for updating or deletion.

However, there seems to be an issue with variable $x as both echo $x->number and echo $x->name return blank values causing the if statement to be false.

    $x = $participant->item($number);

    echo 'number = '.$x->number;
    echo 'name = '.$x->name;

Any assistance on this matter would be greatly appreciated. Thank you.

$number=2;
if ($xml = file_get_contents($file)) 
{
    $xmldoc = new DOMDocument('1.0', 'utf-8');
    $xmldoc->loadXML($xml, LIBXML_NOBLANKS);

    // locate the participants tag
    $root = $xmldoc->getElementsByTagName('participants')->item(0);

    // retrieve the list of participant nodes
    $participant = $xmldoc->getElementsByTagName('participant') ; 
    echo $participant->length; // Number of participant nodes

            // find the node based on the provided number
    $x = $participant->item($number);

    echo 'number = '.$x->number;
    echo 'name = '.$x->name;

    if ($x->number == $number) {
        echo "remove";
        $participant.removeChild($x);
    }
}

Answer №1

This solution worked perfectly for me.

<?php
$number=2;
if ($xml = file_get_contents("a.xml")) 
{
    $xmldoc = new DOMDocument('1.0', 'utf-8');
    $xmldoc->loadXML($xml, LIBXML_NOBLANKS);

    // locating the participants tag
    $root = $xmldoc->getElementsByTagName('participants')->item(0);

    // extracting the list of participant nodes
    $participant = $xmldoc->getElementsByTagName('participant'); 
    $participant->length; // Counting the number of participant nodes

            // fetching the node with specific number
    $name_get = $participant->item($number-1)->getElementsByTagName('number')->item(0)->nodeValue;
    $number_get = $participant->item($number-1)->getElementsByTagName('number')->item(0)->nodeValue;

    echo 'number = '.$name_get;
    echo 'name = '.$number_get;

    if ($number_get == $number) {
        echo "remove";
        $removing_node = $participant->item($number_get-1);
        $root->removeChild($removing_node);
    }
}
echo $xmldoc->saveXML();

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

Struggling to make the fgetcsv file function seamlessly with my MySQL database

I have been attempting to use the fgetcsv function to import all rows of a CSV file into my database. This functionality should be straightforward, but for some reason it is not working as expected. Below is the code I am using: <?php $file = $_FILES[ ...

Executing a Symfony 3 Doctrine query to retrieve data with a related entity

I need help with the following function: /** * * {@inheritDoc} * @see \AppBundle\Interfaces\CrudManagerInterface::search() * * @return Member[] */ public function search(array $searchParams, array $order , ...

Is it possible to have nested associations within Shopware 6?

Within my EntityDefinition, there is an association: ... class ParentEntityDefinition extends EntityDefinition { ... protected function defineFields(): FieldCollection { return new FieldCollection([ (new OneToOn ...

Building Secure Authentication in Laravel 5.8 Using a Custom Table with Additional Fields

In the process of developing my Laravel 5.8 application, I encountered an issue with integrating custom fields into the authentication process for users registered in a SQL table from a pre-existing app. Despite correctly setting up the SQL connection in t ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

"Unlock special birthday surprises with our exclusive AJAX birthday code

Looking for assistance to update the code snippet below for the current date: For example, if today is 18/04/2014, then: day=18 month=04 year=14 If you don't understand: <select name="day" id="day"> <option value="na">day</option> ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

What is the proper method for submitting a mail form via AJAX without using jQuery?

Currently, I am working on integrating a PHP mail form with AJAX. The aim is to create a straightforward form that collects user information such as phone numbers and sends it to my email address. While I have managed to set up the form to send emails usi ...

Why does my ajax request show the result in the php file rather than redirecting to the html page?

I've developed a series of AJAX functions that retrieve data from a PHP file. However, one of the functions redirects to the PHP file to fetch data but fails to return to the HTML page for data insertion. Here is the code used to fetch a table from a ...

Dealing with incoming data in a yii2 RESTful service

When sending an array using $http post, I follow this approach: var results = services.transaction('orderdetails/insert', {customer_id: $scope.order.customer_id, data: $scope.orderDetail}); The variable $scope.orderdetail ...

Building header row using foreach loop in Maatwebsite Excel with Laravel

I am trying to create an Excel file from HTML using Maatwebsite in Laravel, based on the selected MONTH AND YEAR. Below is a snippet of my HTML view. The highlighted area represents the header, which generates data based on the chosen month and year. It d ...

What is the best way to narrow down a Magento product collection by using multiple attribute conditions?

Recently, I decided to add a location attribute to my products and wanted to filter them based on distance from a specific location using geocodes. However, the code snippet below has not been successful in achieving this functionality. $productCollection ...

Calculate the straight line path between points A and B using latitude and longitude coordinates. Determine if a given point is within a certain distance from

After struggling with this problem for a couple of days, I still haven't found a solution :( There is a route on the map from point A to point B in a straight line. Both points have latitude and longitude coordinates. My goal is to determine if point ...

Guide for displaying SQL data in an HTML table

I am currently working on transferring my SQL data to an HTML format. The code I have so far is not functioning as expected. I attempted to include HTML within my PHP code, and now I am considering if it would be better to do it the other way around (emb ...

php If the class attribute does not exist, preg_replace should ignore it

Hello, I have the following piece of code: $content1 = '<img src="image1.png" class="image1"><img src="image2.png"><img src="image3.png" class="image3">'; When I apply this code: preg_replace('~<img\s*.*?\s* ...

Access the value of a submitted form using jQuery, when there are multiple forms with identical class names

I've looked for a solution here but couldn't find one that meets my needs. I have multiple forms with the class name .sbt-form: <form class='sbt-form'> <input name='kord' val=1/> </form> <form class= ...

Secretly stashed away on internet browsers but easily found on Windows Explorer

I seem to be facing a problem that is reminiscent of this After cloning a Laravel project from Github and setting it up on my local Wamp server with a designated hostname, I encountered a "500 internal server error" when trying to access the project throu ...

What could possibly be causing issues with this query to the database?

-Problem Still Unsolved- I am facing issues with calling a database, retrieving all the rows from a table and storing them in an array. I then try to pass this table as JSON data to my JavaScript and use it as parameters for a function. But when I run the ...