【问题标题】:Extracting price from an html string and convert to xml从 html 字符串中提取价格并转换为 xml
【发布时间】:2012-11-05 12:10:05
【问题描述】:

这是我需要提取价格的数据字符串示例。

“价格 475 000 卢比 - 雪佛兰 AVEO LS // 9 月 11 日 6,000 公里 - 红色.. 完整选项.. 手动 5 门 // 掀背车联系我,电话 786 8394”

我在爬取特定网站后有很多这样的字符串,字符串中可以有任何数字或单词。

我尝试用空格分隔每个单词并将其存储在数组 $arr 中。我已经声明了另一个数组来存储价格 $arrPrice 的标识符。 如果找到单词 price 或 rs,则数据(例如 475 000)存储在变量 $price 中。然而,由于我已经用空间爆炸了它,它没有考虑到 000 。我在 xml 标记中只得到 475。

执行此操作的有效方法可能是使用正则表达式,但我不擅长它。如果有人可以帮助我,不胜感激。

到目前为止,在我的代码下方查找,

谢谢!

    <?php


    foreach($html->find('div.field-content') as $e) {//find the h3 element that contains class field content


    $arrPrice = array("rs", "price","rs."); // an array of identifiers to retrieve price

    $str = $e->innertext;// crawled data from a website
    $str = strtolower($str); //converting string to lower case
    $arr = explode(" ", $str);//creating an array of the string by seperating it from the spaces

    if (strlen($str) > 0) {
        $price='';

        for ($i = 0; $i < sizeof($arr); $i++) {

            //finding price 
            for ($j = 0; $j < sizeof($arrPrice); $j++) {
                if ($arr[$i]==$arrPrice[$j]) {
                    $price = $arr[$i+1];
                    //echo 'Price='.$arr[$i+1];

                }
            }   

        }
        $xml.="<Cars>";
        $xml.="<Price>".$price."</Price>";
        $xml.="</Cars>";
    } 

    else {
        echo "String is blank";
    }


}

$file = fopen('data.xml','w');
if(!$file) {
    die('Error cannot create XML file');
}
fwrite($file,$xml);
fclose($file);

?>

【问题讨论】:

  • 价格总是在同一个位置吗?
  • 不,它不是标准的,它可以在任何位置。

标签: php html xml


【解决方案1】:
if ( $arr[$i] == $arrPrice[$j] ) {
  $price = $arr[$i+1];
  if ( isset( $arr[$i+2] ) && is_numeric( $arr[$i+2] ) ) {
    $price .= $arr[$i+2];
  }
}

等等..

【讨论】:

  • 感谢萨尔曼。正如我所提到的,我有几个字符串已被抓取,但我没有在其各自的 xml 标签中获取每个价格。
  • 也许你必须编写不同的逻辑来解析不同的字符串。
  • 我正在考虑使用 preg_match_all() 但正如我所说我不擅长正则表达式:(
猜你喜欢
  • 1970-01-01
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2012-07-19
相关资源
最近更新 更多