Frage

I have the following html structure:

<span class="1">
    <span class="name">
    </span>
    <span class="books">
        <span class="english">
        </span>
        <span class="english">
        </span>
    </span>
</span>
<span class="2">
    <span class="name">
    </span>
    <span class="books">
        <span class="english">
        </span>
        <span class="english">
        </span>
    </span>
</span>
...

I am using the following function to retrieve it:

$oDomObject = $oDomXpath->query("//span[number(@class)=number(@class)]");

How can I store the values in a PHP array keeping the nesting order?

foreach ($oDomObject as $oObject) {
    ..*SOMETHING*..
}

Thank you for your help!

War es hilfreich?

Lösung

You will want to build a recursive function that resembles the following.

WARNING: Not-tested and may require some tweaking. But this should put your head in the right place.

foreach ($oDomObject as $oObject) {
  $myArray[] = getChildren($oObject);
}

function getChildren($nodeObj) {
  retArray = array();
  if($nodeObj->hasChildren()) {
    $retArray[] = getChildren($nodeObj);
  } else {
    $retArray[] = $nodeObj->nodeValue;
  }
  return $retArray;
}

What it does: If it encounters a node without children, it appends the value to the array. If not, it appends an array of the children's values to the array. This occurs ad nauseam, and as deeply as you can wrap your head around.

Things to think about:

  1. What do I want my array to look like when this finishes, because with certain levels of depth, this gets very ridiculous and very annoying to traverse.

  2. Why am I appending to an array, which I am likely to loop through again, instead of handling the desired operation right now?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top