Error in PHP XPath query occurs following DOM adjustment

Every time I attempt to XPath-query a recently created node, I encounter the message

PHP Notice:  Trying to get property of non-object in ...
.

The structure of my XML file is as follows:

<products xmlns='http://example.com/products'>

    <product id='1'>

        <name>Product name</name>

    </product>

</products>

In my PHP code, I use XPath to retrieve an existing <product> and then another query for its <name>, which functions properly.

However, when I add a new <product> with a child <name> element to the root DOM and execute the second query on the newly added elements, retrieving the attribute works fine. But the second query, which should obtain the value of the first child <name>, fails with the PHP Notice

Trying to get property of non-object in ...
.

$xmlFile = __DIR__ . '/products.xml';

$xml = new DOMDocument();

$xml->load($xmlFile);

$xml->formatOutput = true;


$xpath = new DOMXPath($xml);

$xpath->registerNamespace('p', $xml->lookupNamespaceUri($xml->namespaceURI));

$product1 = Product::$xpath->query("//p:product[@id=1]")->item(0);

$product1Id = $product1->attributes->getNamedItem('id')->nodeValue;

$product1Name = $xpath->query("p:name", $product1)->item(0)->nodeValue;


$product2Node = $xml->createElement('product');

$product2Node->setAttribute('id', '2');


$product2NameNode = $xml->createElement('name', 'Test');

$product2Node->appendChild($product2NameNode);


$product2 = $xml->documentElement->appendChild($product2Node);



$product2Id = $product2->attributes->getNamedItem('id')->nodeValue;


$product2Name = $xpath->query("p:name", $product2)->item(0)->nodeValue;

$xml->save($xmlFile);

Upon execution of the PHP script, the XML displays correctly:

<products xmlns='http://example.com/products'>

    <product id='1'>

        <name>Product name</name>

    </product>

    <product id='2'>

        <name>Test</name>

    </product>

</products>

I am currently facing a roadblock with this issue. I have attempted various solutions such as saving the XML before querying, reloading the XML post-saving, recreating the XPath object, etc.

Answer №1

To handle elements in the 'http://example.com/products' namespace, it is recommended to use the createElementNS function instead of createElement. Additionally, you may find it useful to explore the documentation for createElementNS and setAttributeNS method for setting attributes within a specific namespace.

$productNode = $xml->createElementNS('http://example.com/products', 'product');
$productNode->setAttribute('id', '2');

$productNameNode = $xml->createElementNS('http://example.com/products', 'name', 'Test');
$productNode->appendChild($productNameNode);

If reloading the XML after saving did not work as expected, there might have been an issue with the reload process. Without the code snippet for the reload attempt, pinpointing the problem becomes challenging.

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

Swapping out the initial occurrence of every word in the list with a hyperlink

I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of ...

Melodic Streaming Platform

I currently have a client-side application built using React. I have a collection of music stored on my Google Drive that I would like to stream online continuously. I lack experience in server-side programming. Can you suggest any resources or steps I s ...

PHP seems to be resistant to receiving data from ajax requests

I am attempting to develop a drag and drop file upload feature without using a traditional form, utilizing JavaScript's FormData. However, I am encountering an issue where PHP does not seem to be receiving the uploaded file. Could there be some missin ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question: <li class="disabled-result" data-option-array-index="1" style="">4" (0)</li> Here is my attempt at using JavaScript to hide this list item, but it's not working as expected: var xpat ...

What is the best way to display a list of items in Vue JS while maintaining the

Looking to display my Vue.js list in reverse order using v-for without altering the original object. The default HTML list displays from top to bottom, but I want to append items from bottom to top on the DOM. Telegram web messages list achieves this wit ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

When using PHP, JavaScript, and HTML, you can trigger an image upload immediately after choosing a file using the

I currently have a small form with two buttons - one for browsing and another for uploading an image. I feel that having two separate buttons for this purpose is unnecessary. Is there a way to combine the browse and upload functions into just one button? ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

Tips for managing both DOM manipulation and state changes at the same time in AngularJS

<div my-custom-directive> <button id="myButton" ng-click="handleClick(mymodel.id)"><button> </div> app.controller('myCtrl', function($scope) { $scope.handleClick = function(id) { //Perform state change here without ...

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...