我已经尝试过 SimpleXMLElement XPath 方法和 DOMDocument XPath 方法,但似乎都无法让事情变得直接,但至少使用 SimpleXMLElement 路由,我实际上可以打印出结果 var 并查看发生了什么。(见下面的结果)
我想使用 XPath 查询而不必遍历结果。我想我只想像访问数组一样访问结果,但问题似乎超出了该结果数组中的 SimpleXMLElement 对象。
我正在通过具有特定类的 div 查询 HTML 片段。虽然这个特定类有几个 div,所以它们都被返回,这很好。这就是我想要的。但是现在我想访问每个并获取它们的值,在大多数情况下只有它们有子 div。
这是我用来执行 XPath 查询的行:
$stats = $xml->xpath("//div[contains(@class,'line-item')]");
这是结果的 print_r() 输出:
// 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
)
)
现在,因为我知道每个值在哪里,我想我可以像这样访问它们:
$y['clicks'] = "{$stats[4]['div'][0]}: {$stats[5]['div'][1]}\n";
$y['ordered'] = "{$stats[3]['div'][0]}: {$stats[4]['div'][1]}\n";
$y['shipped'] = "{$stats[0]['div'][0]}: {$stats[0]['div'][1]}\n";
$y['conversion'] = "{$stats[5]['div'][0]}: {$stats[6]['div'][1]}\n"; // Doesn't work
$y['rate'] = "{$stats[1]['div'][0]}: {$stats[4]['div'][1]}\n"; // Neither encased in {}
$y['total'] = 'Yesterday\'s Earnings: '.$stats[1]['div'][1]."\n"; // Nor as concatenated
明显的问题是 SimpleXMLElement 对象夹在 $stats 数组中的项目和我所追求的 ['div'] 数组的子项值之间,它们隐藏在那些 SimpleXMLElement 对象后面。
那么如何在不循环 $stats 数组的情况下获得 SimpleXMLElement 对象之外的那些值呢?有什么类似于我上面已经尝试过的吗?