问题
Possible Duplicate:
Preg_match_all <a href
How to parse and process HTML with PHP?
I have used curl to extract the source of a page and need to extract some values from the curl output.
Part of the output looks like this:
<div class="detailInfo">
<label>Manufacturer code/Gas council no:
</label>BKSWX5506</div>
<div class="detailInfo"></div>
<div class="detailInfo">
<div>
<label>Retail price:</label><span>£12.30</span>
</div>
<div>
<label>Net buying price:</label><span>£7.47</span>
</div>
</div>
From that output I need to get the code after "Manufacturer code/Gas council no:" and both of the prices all in separate strings.
Can anyone help me with this?
Thanks :)
回答1:
try this :
<?php
$output = '<div class="detailInfo">
<label>Manufacturer code/Gas council no:
</label>BKSWX5506</div>
<div class="detailInfo"></div>
<div class="detailInfo">
<div>
<label>Retail price:</label><span>£12.30</span>
</div>
<div>
<label>Net buying price:</label><span>£7.47</span>
</div>
</div>';
$outputArray = explode("</label>", str_replace("<label>","</label>",strip_tags($output, '<label>')));
echo "<pre>";
print_r($outputArray);
echo "</pre>";
exit;
?>
output :
Array
(
[0] =>
[1] => Manufacturer code/Gas council no:
[2] => BKSWX5506
[3] => Retail price:
[4] => £12.30
[5] => Net buying price:
[6] => £7.47
)
回答2:
The following is a general purpose routine that you can use to get some xpath's to text parts you're looking for. It should give you a first start as it shows as well how to run a xpath query:
$searches = array('BKSWX5506', '£12.30', '£7.47');
$doc = new DOMDocument();
$doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">'.$html);
$xp = new DOMXPath($doc);
foreach($searches as $search)
{
$expression = '//text()[contains(., "'.$search.'")]';
$result = $xp->query($expression);
foreach($result as $found)
{
/* @var $found DOMNode */
printf("%s: %s\n", $found->getNodePath(), $found->nodeValue);
}
}
For the $html
content you've provided it does the following output:
/html/body/div[1]/text()[2]: BKSWX5506
/html/body/div[3]/div[1]/span/text(): £12.30
/html/body/div[3]/div[2]/span/text(): £7.47
Using these paths would reveal the information again:
$number = $xp->evaluate('string(/html/body/div[1]/text()[2])'); # BKSWX5506
As you can see, you can xpath for both: analyzing documents to obtain specific values and then use the information gathered as a pattern.
来源:https://stackoverflow.com/questions/10428504/extracting-values-from-string-with-php