1

How are we supposed to check the value for the following HTML5 attributes?

<input type="text" required />

Or this:

<video src="" autoplay></video>

This is the code I use:

$dom->loadHTML($html);
$xpath = new DOMXPath($dom);    
$result = $xpath->query('//input');

foreach($result as $item) var_dump($item->getAttribute('required'));

The required attribute may or may not be set, the result stays the same:

string(0) ""

If getAttribute would return null instead of an empty string when the attribute is not defined it would make more sense.

I am aware we can use something like required="required" but I can't be sure that the attribute is in that form since the code that gets parse may differ.

2 Answers 2

2

I think the rule is that if the attribute exists, then apply the action. So try hasAttribute('required')

Sign up to request clarification or add additional context in comments.

1 Comment

Great! This seems to work correctly. Why did I overlook that function?
2

try

$item['required']

instead of

$item->getAttribute('required')

2 Comments

$item is an object so we can't treat it like an array.
In php if you implement ArrayAccess then any object can be used as array . (Bassically __set , __get magic function ) simplexml is not exception to it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.