Retrieving attribute values in PHP using XPath

Similar Question:
How can I extract an attribute from an XML node using PHP's DOM Parser?

Can someone help me with extracting the value of an HTML tag?

Here is the HTML code snippet:

<input type="hidden" name="text1" id="text1" value="need to get this">

This is the PHP code I have written so far:

$homepage = file_get_contents('http://www.example.com');
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($homepage);
$xpath = new DOMXpath($doc);
$filtered = $xpath->query("//input[@name='text1']");

How can I access the value as "need to get this"?

Update:

I have managed to make it work and I hope my solution can assist others too. After the above code, I retrieved the value by:

echo $filtered->item(0)->getAttribute('value');

Answer №1

Using XPath, you can easily retrieve the value attribute by using

$xpath->query("//input[@name='text1']/@value");
. From there, you can loop through the list of attribute nodes and access the $value property of each node.

Answer №3

I'm not very familiar with the PHP syntax in this case, but to retrieve the value attribute, you can utilize the following xpath:

//input[@name='text1']/@value

However, it's important to note that xpath doesn't directly return strings; instead, it returns nodes. To access the nodeValue of the node, you may use the following code if PHP abides by conventions:

 $xpath->query("//input[@name='text1']/@value")->item(0).nodeValue;

For educational purposes, remember to always reference the nodeValue property. For instance, if you wish to obtain the name of the same element, you would use:

 $xpath->query("//input[@name]/@name")->item(0).nodeValue;

It is advisable to validate that the query provides a non-null value before accessing the nodeValue property.

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

Tips for showcasing multiple tables based on certain criteria

Hey there, I'm currently working on an inventory page where I want to display multiple tables based on department values. The goal is to have each department in its own table instead of all merged into one. It would definitely make the page easier to ...

Executing a PHP file with a PDO connection in the terminal is failing to establish a connection

When running a certain PHP file in the browser, everything works perfectly fine. However, when I try to execute it in the terminal, php /opt/lampp/htdocs/xampp/site_name/update_db.php the PDO include and connection don't seem to function properl ...

Finding the initial channel points icon on twitch.tv/esl_csgo through Selenium and Python

While watching the livestream on the ESL CS:GO Twitch channel, I encountered an issue when trying to click on the channel points button/icon. Every time I attempt to do so, I receive an error message stating: "no such element: Unable to locate element." De ...

MySQL - To escape or not to escape variables, that is the question!

I'm curious about whether it is essential to escape internal variables that originate from the database and are user-input. Is it simply a performance drain or does it enhance security? Appreciate your feedback! ...

How to block manual POST requests in a specific system

On my PHP site, I have a system similar to Twitter where users can follow each other. To follow someone, a user simply clicks on the follow button on the desired user's profile. Once clicked, an AJAX post request is sent with the ID of the user being ...

While using Tcpdf, I encounter an issue where the textarea value I pass is not being printed in the desired format

Currently, I am experimenting with TCPDF to create PDF files from HTML. However, I have encountered an issue where passing a variable containing text results in the text being printed on separate pages for each line. Is there a way to ensure that the tex ...

Guide to capturing the name H MATTHEWS from a website's HTML using Selenium with Python

When utilizing the 'contains' function, how can I extract specific information from this particular HTML structure? My goal is to gather the name "H MATTHEWS". HTML: <p> <strong>Date Published:</strong> &nbsp; 20 APRIL 2020 ...

A method for selecting the checkbox in a mat-row that corresponds to a certain text with Selenium

I want to select the checkbox within a nested mat-row: <mat-row _ngcontent-dac-c252="" role="row" class="mat-row cdk-row ng-star-inserted"> <mat-cell _ngcontent-dac-c252="" role="cell" class=&quo ...

Calculate the total sum of values in a MySQL column and then group the results

I'm currently working on a quiz website and looking to create a leaderboard. The user scores are stored in a database table named 'user_record' with the following structure: 'user_id' - varchar(254) -holds the user id for a score ...

Clearing up confusion around identifying checkbox elements using XPath in Selenium WebDriver with Java, specifically within a

HTML code <div class="modal-footer slds-modal__footer" data-aura-rendered-by="2805:0"> <div class="rssDialogText grantAccessCheckbox packagingSetupUIRssDialogFooter" data-aura-rendered-by="2595:0" data-aura-class="packagingSetupUIRssDialogFooter" ...

What is the best method for converting a date from an array format to a standard date format?

After retrieving a date from the database in the format ["1982-02-25"], I would like it to be displayed as 1982-02-25. Any suggestions on how to achieve this? ...

Selenium web driver use case for hovering mouse actions

Having trouble with mouse hover operation. The code works sometimes and not others. Here is my code: driver.get("http:obsessory.com/"); Actions action = new Actions(driver); WebElement mainMenu = driver.findElement(By.xpath("//a[@href='/shop/m/women ...

Error 4 encountered when attempting to upload files using Ajax to a PHP server

On my website, there is a form that looks like this: <form style="width:100%; clear:both; margin-top:50px; background:#fff; border:1px solid green" id="upload_form" enctype="multipart/form-data" class="form" action="" method="post"> <fieldse ...

Substitute All Non-Linguistic Symbols Apart from Language-Specific Ones

Stripping away everything from the string except for language-specific special characters can be tricky. I've attempted to achieve this using the following method: $string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string); Ho ...

Organize based on primary website address

Here is a collection of URLs I need to organize: http://www.example.com/ http://www.another.com/1/hi-hello http://www.example.com/index.php http://www.another.com/1/archive http://www.example.com/about.php http://www.another.com/ All these URLs are curre ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

Using Laravel: A guide to incorporating conditional statements within curly braces {{ }}

When working on my Laravel application, I often need to pass search filters through links. In the past, this code worked perfectly in Laravel 4, but now that I'm transitioning to Laravel 8, I'm encountering an error. {{ link_to_route('workpr ...

Accessing OrientDB from PHP

Looking for assistance with creating a PHP adapter for the binary API of OrientDB, specifically regarding socket communications. Struggling to establish a connection between PHP and OrientDB, seeking help from someone familiar with raw socket communicatio ...

Retrieve individual data rows from a MySQL table consecutively

Is there a way to retrieve data from a MySQL table one by one in PHP? data1 // wait 5 seconds data2 // wait 5 seconds I'm looking for a solution where I can fetch the data sequentially like this. Any suggestions on how to achieve this? ...

steps to verify the status of a sent request

I am utilizing the contenteditable property in a p tag. My code is as follows: <p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px ">&l ...