xml - In PHP, how to saveXML with the attributes sorted?
Get the solution ↓↓↓If I have a DOMDocument and I would like to parse it into a string, how do I ensure that the attributes will be sorted in some deterministic/normalized order (lexicographically based on the attribute name would be nice)?
For example how can I make this printequal
instead ofnotequal
?
$dom = new DOMDocument();
$dom->loadXML('<tag a="a" b="b"/>');
$dom2 = new DOMDocument();
$dom2->loadXML('<tag b="b" a="a"/>');
echo $dom->saveXML() === $dom2->saveXML() ? "equal" : "notequal";
According to the documentation,saveXML
only supported option isLIBXML_NOEMPTYTAG
.
Answer
Solution:
DOMNode::C14N()
canonicalizes nodes to a string.
$expected = new DOMDocument();
$expected->loadXML('<tag a="a" b="b"/>');
$actual = new DOMDocument();
$actual->loadXML('<tag b="b" a="a"/>');
echo $expected->C14N() === $actual->C14N() ? "equal" : "notequal";
Output:
equal
If you're write unit tests - PHPUnit has specific assertions for XML.
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object of class stdclass could not be converted to string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.