Question

I'm using phpQuery to parse a some HTML that have a similar to this structure:

<div>
    <span>Name</span>
    <span>John</span>
    <span>Age</span>
    <span>23</span>
    <span>Location</span>
    <span>London</span>
</div>

I need to collect all this information into an associative array, so I'm doing something like this:

$doc = new phpQuery($html);
foreach($doc['div span'] as $span){
    $text = pq($span)->text();
    // do some other stuff with $text
}

Note that $doc and $doc['div span'] are phpQueryObjects that implement Iterator, Countable and ArrayAccess.

Now, to correlate this data, I'm forced to use a variable where I store the current state (title or value) which is not quite elegant. What I would like to do is to be able to iterate 2 items at a time. One solution I found was to do iterate through all the object using foreach adding all the items to an array and after that just use next() or each() on that array to get 2 items at a time in a while loop, but this is not nice at all. Keep in mind that using next() or each() on a phpQuery object I just get it's public properties and that's not what I want at all. Is there a way to do this and have a nice code?


Note: Although this question is related to phpQuery, I think it's a general php question and does not involve phpQuery knowledge.

Was it helpful?

Solution

As stated in the question, phpQuery implements Iterator.

So I'd say this is probably the cleanest way you can do what you want:

$doc = new phpQuery($html);
$elements = $doc['div span'];

foreach($elements as $span){
    $key = pq($span)->text();
    $elements->next();
    $value = pq($elements->current())->text();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top