gpt4 book ai didi

php - DOMXPath/PHP - 仅在特定出现后获取值

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:24 25 4
gpt4 key购买 nike

伙计们,我正在解析 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)?

提前致谢!

最佳答案

$specific 有您要查找的字符串。将代码中的 foreach 更改为:

$specific = '7 (41)';

foreach ($collections[1]->SizeVariants as $item) {
$SizeName = $item->SizeName;

if(trim($SizeName) == trim($specific)) {

$PriceUnformated = $item->ProdSizePrices->SellPrice;

$find = array('£');
$replace = array('');
$Price = str_replace($find, $replace, $PriceUnformated);

echo "SizeName: <b>$SizeName</b> - Price: <b>$Price</b><br>";
}
}

关于php - DOMXPath/PHP - 仅在特定出现后获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com