1

I have this XML:

  <picture id="2">
    <title>B</title>
  </picture>
  <picture id="3">
    <title>C</title>
  </picture>
  <picture id="0">
    <title>A</title>
  </picture>

Trying to achieve this:

  <picture id="1">
    <title>B</title>
  </picture>
  <picture id="2">
    <title>C</title>
  </picture>
  <picture id="0">
    <title>A</title>
  </picture>

Using this to get a list of 'id' attribute values:

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
$arrayCurrent = array();
foreach($picture as $value) {
    $arrayCurrent[] = (string)$value['id'];
}
sort($arrayCurrent); // put XML into numerical 'id' order
print_r($arrayCurrent);

It returns: Array ( [0] => 0 [1] => 2 [2] => 3 ) Any ideas how to re-index like so: 0, 1, 2 and save the appropriate 'id' attributes back to their correct positions in the XML doc?

Thanks, Andy

0

2 Answers 2

0

In XML order of nodes in same level is doesn't matter then you can't do this by theory, by practice user other library.

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

4 Comments

I don't understand your answer. The physical order of the nodes in the XML document is irrelevant which is why I have given them 'id' attributes so I can display them in the order I choose. The id's need to be sorted so that they go: 0,1,2,3,4,5 etc with no gaps instead of 0,1,3,4,6,9 etc.
@andy What you describe is not what is shown in the example. In the example, they pictures are ordered 1,2,0, which implies you want to sort the IDs by the letters in the title. Please clarify what you are trying to achieve, e.g. what the rule for sorting is.
@Gordon Thanks for replying, I was trying to show that I'm not sorting the xml as it appears in the xml file, the nodes are in a somewhat random order. The id attribute needs to be kept in the same numerical order, but 're-indexed' to make the id numbers consecutive.
I've been given a solution that works for me so I'll post it on here, I'm presume there are other ways of doing it.
0

Numerical id order is maintained and made consecutive:

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
usort($picture, create_function('$a,$b', 'return (string)$a["id"] - (string)$b["id"];'));
foreach ($pictures as $index => $node) $node["id"] = $index;

Comments

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.