XPath result as array of named keys in PHP
Dom parsing with PHP is a pain. Certainly if you take a look at how easy it is with JavaScript.
This is how I get all attributes from each input element:
$dom = new DOMDocumen开发者_如何学Got();
$dom->loadHTML('<form><input type="text" required /><input type="password" name="password" required /></form>');
$xpath = new DOMXPath($dom);
$result = $xpath->query('//input/@*');
foreach($result as $key=>$value) {
echo $key . ': ' . $value->nodeValue . '<br />';
}
How can you get named keys instead of numbered keys?
Dom parsing in PHP is the same as JS since they use the same interface (the standard Document Object Model)... The only difference is that in JS it's easy to introspect the individual elements (whereas in PHP it's kept below the API since it's implemented in C).
Now, for your exact question, the return type of $value
is DomAttr. So this should do it for you:
echo $value->name . ': ' . $value->value . '<br />';
Edit: Regarding your comment. Do it this way:
$result = $xpath->query('//input');
$inputs = array();
foreach($result as $element) {
$current = array();
foreach ($element->attributes as $attribute) {
$current[$attribute->name] = $attribute->value;
}
$inputs[] = $current;
}
精彩评论