XPath to XML with PHP

XPath to XML with PHP

Sometimes the development of applications that deal with the XML comes to the point when the developer has to build XML document using only XPath location of elements and theirs values. For such cases the XPath to XML processor was written, so I hope it will help somebody in converting the XPath sets into documents. It is very light and performs basic document construction without any validations (we assume that no XML Schema is available).

You can checkout the XPath to XML processor at https://github.com/sashuk/xpathtoxml. Below the example of input array (in JSON format, so you can just do the json_decode(INPUTSTRING, true); over it) and the resulting output (in XML) are listed.

If there is any question or improvement, please, make a ticket at the GitHub page.

 

{
  "\/rootelement[1]\/hierarchyelement[1]\/leafelement": {
    "values": [
      "Hierarchy 1 Leaf 1",
      "Hierarchy 1 Leaf 2"
    ],
    "attributes": [
      {
        "name": "firstLeafAttribute",
        "values": [
          "leaf 1 attribute 1",
          "leaf 2 attribute 1"
        ]
      },
      {
        "name": "secondLeafAttribute",
        "values": [
          "leaf 1 attribute 2",
          "leaf 2 attribute 2"
        ]
      }
    ]
  },
  "\/rootelement[1]\/hierarchyelement[2]": {
    "attributes": [
      {
        "name": "test",
        "values": [
          "hierarchyelement 2 attribute value"
        ]
      }
    ]
  },
  "\/rootelement[1]\/hierarchyelement[2]\/leafelement": {
    "values": [
      "Hierarchy 2 Leaf 1",
      "Hierarchy 2 Leaf 2"
    ]
  }
}

..is processed into the..

<?xml version="1.0" encoding="utf-8"?>
<rootelement>
	<hierarchyelement>
		<leafelement firstLeafAttribute="leaf 1 attribute 1" secondLeafAttribute="leaf 1 attribute 2">Hierarchy 1 Leaf 1</leafelement>
		<leafelement firstLeafAttribute="leaf 2 attribute 1" secondLeafAttribute="leaf 2 attribute 2">Hierarchy 1 Leaf 2</leafelement>
	</hierarchyelement>
	<hierarchyelement test="hierarchyelement 2 attribute value">
		<leafelement>Hierarchy 2 Leaf 1</leafelement>
		<leafelement>Hierarchy 2 Leaf 2</leafelement>
	</hierarchyelement>
</rootelement>