その配列をデータベースの結果と比較するために、ノード属性を配列に変換する方法を探しているときに、この質問に出くわしました。https://stackoverflow.com/users/264502/jan-molakからの回答でうまくいきますが、私の場合、ノードに一部の属性がないか、空の文字列である可能性があるという事実は考慮されていません。 、NULLDBから返されるがあります。
これをカバーするために、私はそれを以下の関数に拡張しました。これは他の誰かにも役立つかもしれません。
#Function to convert DOMNode into array with set of attributes, present in the node
#$null will replace empty strings with NULL, if set to true
#$extraAttributes will add any missing attributes as NULL or empty strings. Useful for standartization
public function attributesToArray(\DOMNode $node, bool $null = true, array $extraAttributes = []): array
{
$result = [];
#Iterrate attributes of the node
foreach ($node->attributes as $attrName => $attrValue) {
if ($null && $attrValue === '') {
#Add to resulting array as NULL, if it's empty string
$result[$attrName] = NULL;
} else {
#Add actual value
$result[$attrName] = $attrValue->textContent;
}
}
#Add any additional attributes, that are expected
if (!empty($extraAttributes)) {
foreach ($extraAttributes as $attribute) {
if (!isset($result[$attribute])) {
if ($null) {
#Add as NULL
$result[$attribute] = NULL;
} else {
#Or add as empty string
$result[$attribute] = '';
}
}
}
}
#Return resulting string
return $result;
}
}
属性について話すとき、どういうわけか私にはもう少し「自然」に感じるので、私はに置き換えましnodeValueたが、技術的には、ここでは関係なく同じになります。必要に応じて、この関数は(https://github.com/Simbiat/ArrayHelpers)
の一部としてComposerで使用できます。textContent
Simbiat/ArrayHelpers