这段代码输出的内容类似于下面的描述,我需要将每个输出精确地转换为一个PHPvar
eg:
[product-link]个
[0] »» $var_prod_link_0 = 'the link 0 here';
[1] »» $var_prod_link_1 = 'the link 1 here';
etc..
[product-img-src]个
[0] »» $var_prod_img_0 = 'the image 0 link here';
[1] »» $var_prod_img_1 = 'the image 1 link here';
etc..
[h3-title-text]个
[0] »» $var_title_text_0 = 'the title 0 here';
[1] »» $var_title_text_1 = 'the title 1 here';
etc..
[price]个
[0] »» $var_price_0 = 'the price 0 here';
[1] »» $var_price_1 = 'the price 1 here';
ect..
This is the code:
# set the libxml parameters and create new DOMDocument/XPath objects.
libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->validateOnParse=false;
$dom->strictErrorChecking=false;
$dom->recover=true;
$dom->loadHTML( $html );
libxml_clear_errors();
$xp=new DOMXPath( $dom );
# some basic XPath expressions
$exprs=(object)array(
'product-link' => '//a[@class="product-image-link"]',
'product-img-src' => '//a[@class="product-image-link"]/img',
'h3-title-text' => '//h3[@class="wd-entities-title"]',
'price' => '//span[@class="price"]/span/bdi'
);
# find the keys (for convenience) to be used below
$keys=array_keys( get_object_vars( $exprs ) );
# store results here
$res=array();
# loop through all patterns and issue XPath query.
foreach( $exprs as $key => $expr ){
# add key to output and set as an array.
$res[ $key ]=[];
$col=$xp->query( $expr );
# find the data if the query succeeds
if( $col && $col->length > 0 ){
foreach( $col as $node ){
switch( $key ){
case $keys[0]:$res[$key][]=$node->getAttribute('href');break;
case $keys[1]:$res[$key][]=$node->getAttribute('src');break;
case $keys[2]:$res[$key][]=trim($node->textContent);break;
case $keys[3]:$res[$key][]=trim($node->textContent);break;
}
}
}
}
printf('<pre>%s</pre>',print_r($res,true));
The output from the above code:
Array
(
[product-link] => Array
(
[0] => https://...linkhere
[1] => https://wwwle.com/banana
)
[product-img-src] => Array
(
[0] => https://image-goes-here.jpg
[1] => https://www.example.com/kittykat.jpg
)
[h3-title-text] => Array
(
[0] => The title goes here
[1] => Oh look, another title!
)
[price] => Array
(
[0] => â¬20,00
[1] => â¬540,00
)
)