I've tried both the SimpleXMLElement XPath approach as well as the DOMDocument XPath approach, but cannot seem to get things straight either way, but at least with the SimpleXMLElement route, I could actually print out the results var and see what's going on. (See Results Below)
I want to use XPath querys without having to loop through the results. I guess I just want to access the results like an array, but the issue seems to be getting past the SimpleXMLElement objects within that results array.
I'm querying an HTML snippet by div with a specific class. There are several divs of this particular class though, so all of them are being returned, which is fine. That's what I want. But now I want to access each and get their values, only they have child divs in most cases.
Here's the line I'm using to execute the XPath query:
$stats = $xml->xpath("//div[contains(@class,'line-item')]");
Here's a print_r() output of the results:
// Output of $stats
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item
)
[div] => Array
(
[0] => Total items shipped
[1] => 50
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item-total
)
[div] => Array
(
[0] => TOTAL EARNINGS *
[1] => $267.23
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item-links
)
[a] => View full report
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item
)
[div] => Array
(
[0] => Ordered items
[1] => 42
)
)
[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item
)
[div] => Array
(
[0] => Clicks
[1] => 428
)
)
[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item
)
[div] => Array
(
[0] => Conversion
[1] => 9.81%
)
)
[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => line-item-links
)
[a] => View full report
)
)
Now, since I know where each value is, I thought I could just access them like so:
$y['clicks'] = "{$stats[4]['div'][0]}: {$stats[5]['div'][1]}
";
$y['ordered'] = "{$stats[3]['div'][0]}: {$stats[4]['div'][1]}
";
$y['shipped'] = "{$stats[0]['div'][0]}: {$stats[0]['div'][1]}
";
$y['conversion'] = "{$stats[5]['div'][0]}: {$stats[6]['div'][1]}
"; // Doesn't work
$y['rate'] = "{$stats[1]['div'][0]}: {$stats[4]['div'][1]}
"; // Neither encased in {}
$y['total'] = 'Yesterday\'s Earnings: '.$stats[1]['div'][1]."
"; // Nor as concatenated
The obvious problem is the SimpleXMLElement object wedged in between the items in the $stats array and the ['div'] array whose sub-items' values I'm after, which are hiding behind those SimpleXMLElement objects.
So how would I get at those values beyond the SimpleXMLElement objects, without looping through the $stats array? Anything similar to what I've already tried above?