How to get value by id using DomDocument?

64 Views Asked by At

I am trying to get value of form below using DomDocument but so far still failed

<?php
$string ='<form action="profile" method="post" enctype="multipart/form-data">
    <input type="hidden" name="id_user" id="id_user" value="123">
    <input type="hidden" name="logo" id="logo" value="path/to/logo1.png">
    <input type="hidden" name="status" id="status" value="Ok">
    <input type="submit" value="PROFILE">
</form>';
?>

How to properly use DomDocument in this case?

I was trying below code

$dom = new DomDocument();
$dom->loadHTML($string);
$dom->getElementById("id_user");

I was expecting to get 123 as returned value

2

There are 2 best solutions below

0
KIKO Software On

DomDocument is a bit of a fiddle, but if you follow the documentation you can get there. I found this route:

$dom->getElementById("id_user")->attributes->getNamedItem("value")->value

This returns:

123

See: https://onlinephp.io/c/c37dc

There might be other ways to do the same.

0
Jack Fleeting On

You can try using xpath:

$xpath = new DOMXPath($dom);
echo($xpath->query('//form//input[@id="id_user"]/@value')[0]->value);