将PHP数组输出按顺序转换为指定命名变量的技术需求
从HTML提取商品数据并转换为指定命名规则的PHP变量
现有一段PHP代码,可通过DOMDocument与XPath从HTML中提取商品链接、图片地址、标题、价格等数据并输出为多维数组。需将数组中各子数组的元素按顺序转换为指定命名规则的PHP变量,示例如下:
[product-link]
[0] »» $var_prod_link_0 = '这里是链接0'; [1] »» $var_prod_link_1 = '这里是链接1'; 以此类推..
[product-img-src]
[0] »» $var_prod_img_0 = '这里是图片链接0'; [1] »» $var_prod_img_1 = '这里是图片链接1'; 以此类推..
[h3-title-text]
[0] »» $var_title_text_0 = '这里是标题0'; [1] »» $var_title_text_1 = '这里是标题1'; 以此类推..
[price]
[0] »» $var_price_0 = '这里是价格0'; [1] »» $var_price_1 = '这里是价格1'; 以此类推..
代码实现
// 设置libxml参数并创建DOMDocument和XPath对象 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); // 定义基础XPath表达式 $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' ); // 获取键名(后续方便使用) $keys = array_keys(get_object_vars($exprs)); // 存储提取结果 $res = array(); // 遍历所有表达式并执行XPath查询 foreach ($exprs as $key => $expr) { // 初始化当前键对应的结果数组 $res[$key] = []; $col = $xp->query($expr); // 查询成功时提取数据 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));
代码输出结果
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 ) )
注:价格字段的â¬是编码问题导致的欧元符号乱码,可通过设置字符编码解决。
内容的提问来源于stack exchange,提问作者bpy
相关产品推荐
相关产品推荐

