PHP/HTML DOM解析器-从文本中获取特定部分,然后获取另一个字符串


PHP/HTML DOM Parser - Fetch a Specific part from a text and then get another string

伙计们,我正在编写一个脚本,该脚本使用curl解析链接中的HTML输出数据。

以下是HTML DOM解析器-http://simplehtmldom.sourceforge.net

让我给你看看我的解析器:

<?PHP
include_once('./simple_html_dom.php');
$url = "http://www.sportsdirect.com/muddyfox-cycling-short-sleeved-jersey-mens-636266?colcode=63626622";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
 $str = curl_exec($curl);  
 curl_close($curl); 
$html= str_get_html($str);   

$SIZEID = 'UK: 8-13 Kids / EU: 25-32 Kids';
$occurencies = preg_match_all('/(?<='"SizeName'":'"' . preg_quote($SIZEID, "/") . '")'S+/i', $str, $match);

foreach($html->find('#ulColourImages li') as $selectnocolor)    
$colvarid = $selectnocolor->colvar-id;
$tooltiptext = $selectnocolor->tooltiptext;     

echo "$tooltiptext - $colvarid";

所以当我获取我需要的页面时,我会得到纯文本,我必须从中获得特定的部分。

全文如下:http://pastebin.com/FwK9Z8CP

让我描述一下我需要什么

在文本中,这个特定单词ColVarId总共出现了3次。

在每个CCD_ 2之后都有几个CCD_。

例如,在文本"SellPrice":"£4.49"和这个SellPrice单词中,我得到了有关价格的信息。这就是我最终想要实现的全部,我想得到特定"SellPrice":"MYTargetText" 中包含的价格

我想做什么,但不知道怎么做:

例如,我想获得ColVarId单词第二次出现后的所有文本,然后从提取的文本中,我想选择例如SellPrice的第三次出现,其结构类似于例如"SellPrice":"£4.49",在本例中价格为4.49。所以我想把价格控制在那里。我该怎么做?

我希望我能很好地描述我的问题,你们也能理解我在决赛中想要达到的目标。

提前谢谢。

既然这是php,不如使用json_decode?虽然正则表达式看起来是可靠的,但json_decode将更加可靠,并在将来需要时提供更多访问对象中其他属性的功能。

在下面的解决方案中,我使用preg_replace在字符串的开头字符串出javaScript赋值。然后,我对剩余的json进行解码,以便将数据作为对象。

$colourJavascript = preg_replace('/^[^=]+=/', '', $colourJavascript);
$data = json_decode($colourVariantsInitialData);
print_r($data[0]->SizeVariants[0]->ProdSizePrices->SellPrice);
print_r($data[0]->SizeVariants[1]->ProdSizePrices->SellPrice);
print_r($data[0]->SizeVariants[2]->ProdSizePrices->SellPrice);

如果需要数值,可以使用NumberFormatter提取值,而不是像示例数据中那样格式化的货币。

$formatter = new NumberFormatter("en-GB", 'NumberFormatter::CURRENCY);
$priceRaw = $data[0]->SizeVariants[0]->ProdSizePrices->SellPrice;
print_r($formatter->parse($priceRaw)); 

完整Gist

首先要避免simple_html_dom,它是有史以来最糟糕(最慢)的解析器,而且不那么简单。花点时间学习如何使用DOMDocument和DOMXPath(有很多关于XPath1.0的教程)来完成同样的工作(注意,一旦你学习了php,你就可以将其用于许多其他语言,因为这在任何地方都可以实现)。

第二步是提取json字符串并构建json对象。

一般的建议是:当你已经在鼻子下格式化数据时,使用这种格式,它比字符串方法更方便。

$url = 'http://www.samplehost.com/samplepage.php';
// discard notices and warnings about badly formated html 
libxml_use_internal_errors(true);
$dom = new DOMDocument; 
// or get the file content via curl and use $dom->loadHTML($content);
$dom->loadHTMLFile($url); 
$xp = new DOMXPath($dom);
// '//' means everywhere in the DOM tree, 'script' is the target node,
// and [...] encloses conditions about this node:
// normalize-space is used here to trim leading spaces,
// the dot refers to the current node content
$qry = '//script[starts-with(normalize-space(.), "var colourVariantsInitialData")]';
// an xpath query returns a nodeList, to get the first (and unique here)
// item of the list, you need to use ->item(0)
$rawtxt = $xp->query($qry)->item(0)->nodeValue;
// extraction of the json string and creation of a json object 
$jsonStart = strpos($rawtxt, '[');
$jsonEnd = strrpos($rawtxt, ']');
$collections = json_decode(substr($rawtxt, $jsonStart, $jsonEnd - $jsonStart + 1));
// Then you can easily extract what you want from the json object 
echo "collection id: " . $collections[1]->ColVarId . "'n";
foreach ($collections[1]->SizeVariants as $item) {
    printf("%-30s't%s'n", $item->SizeName, $item->ProdSizePrices->SellPrice);
}

您在Pastebin链接到的示例看起来像JavaScript,而不是HTML。完全不同的语言。您绝对不应该使用正则表达式来解析PHP本机支持的数据格式。

理想情况下,它应该用JavaScript进行解析。如果必须在PHP中解析它,那么去掉JavaScript部分(开头为var colourVariantsInitialData=,结尾为分号),并使用json_decode()将JSON部分拖入PHP数组。例如:

<?php
$s = file_get_contents("http://example.com/path/to/data.json");
preg_match('/^[^=]+ *= *(.*);$/', $s, $a);
$output = json_decode($a[1]);
// Now simply go find SellPrice inside ColVarId.

免责声明:这只适用于PHP,并且只有当您真的要使用regex解析它时。

这是您的正则表达式,它提取了3个"SellPrice":"字符串:

 ColVarId.*?'K("SellPrice":"[^"]+")

这是一个演示。

'K在PHP中的使用是可能的,因为它使用PCRE库。'K省略了直到该运算符的整个匹配。您将收到您的SellPrice详细信息。