【发布时间】:2015-03-31 19:38:29
【问题描述】:
伙计们,我正在解析一个 URL 以获取 HTML dom 元素。
这是我的代码:
<?PHP
$url = 'http://www.sportsdirect.com/nike-satire-mens-skate-shoes-242188?colcode=24218822';
libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTMLFile($url);
$xp = new DOMXPath($dom);
$qry = '//script[starts-with(normalize-space(.), "var colourVariantsInitialData")]';
$rawtxt = $xp->query($qry)->item(0)->nodeValue;
$jsonStart = strpos($rawtxt, '[');
$jsonEnd = strrpos($rawtxt, ']');
$collections = json_decode(substr($rawtxt, $jsonStart, $jsonEnd - $jsonStart + 1));
foreach ($collections[1]->SizeVariants as $item) {
$SizeName = $item->SizeName;
$PriceUnformated = $item->ProdSizePrices->SellPrice;
$find = array('£');
$replace = array('');
$Price = str_replace($find, $replace, $PriceUnformated);
echo "SizeName: <b>$SizeName</b> - Price: <b>$Price</b><br>";
}
此代码正在从输出源的脚本中获取“文本”。 以下是此脚本的完整文本:http://pastebin.com/FwK9Z8CP
我的代码给出以下结果:
SizeName: 7 (41) - Price: 27.00
SizeName: 8 (42.5) - Price: 36.00
SizeName: 9 (44) - Price: 36.00
SizeName: 9.5 (44.5) - Price: 36.00
SizeName: 11 (46) - Price: 36.00
我的问题是:
如何仅获取特定 SizeName 的结果,例如 SizeName 7 (41)?
提前致谢!
【问题讨论】:
标签: php xml json algorithm domxpath