douhuitan5863 2010-04-29 22:20
浏览 77
已采纳

像sed / awk / grep一样帮助PHP数据修改

Ok guys.. I have a HTML i need to parse into a php script and mangle the data around abit. For best explanation I will show how I would do this in a bash script using awk, grep, egrep, and sed through a god awful set of pipes. Commented for clarity.

curl -s http://myhost.net/mysite/           | \ # retr the document 
       awk '/\/\action/,/submit/'           | \ # Extract only the form element
       egrep -v "delete|submit"             | \ # Remove the action lines 
       sed 's/^[ \t]*//;s/[ \t]*$//'        | \ # Trim extra whitespaces etc. 
       sed -n -e ":a" -e "$ s/
//gp;N;b a" | \ # Remove every line break
       sed '{s|<br />|<br />
|g}'          | \ # Insert new line breaks after <br />
       grep "onemyndseye@localhost"         | \ # Get lines containing my local email
       sed  '{s/\[[^|]*\]//g}'              | \ # Remove my email from the line

These commands take the form element that looks like this:

<form action="/action" method="post">
    <input type="checkbox" id="D1" name="D1" /><a href="http://www.linux.com/rss/feeds.php">
        http://www.linux.com/rss/feeds.php
    </a> [email: 
        onemyndseye@localhost (Default)
    ]<br />         
    <input type="checkbox" id="D2" name="D2" /><a href="http://www.ubuntu.com/rss.xml">
        http://www.ubuntu.com/rss.xml
    </a> [email: 
        onemyndseye@localhost (Default)
    ]<br /> 
    <input type="submit" name="delete_submit" value="Delete Selected" />

And mangles it into complete one-line input statements.. Ready to be inserted into another form:

<input type="checkbox" id="D1" name="D1" /><a href="http://www.linux.com/rss/feeds.php">http://www.linux.com/rss/feeds.php</a> <br />
<input type="checkbox" id="D2" name="D2" /><a href="http://www.ubuntu.com/rss.xml">http://www.ubuntu.com/rss.xml</a> <br />

The big question is how to accomplish this in PHP? I am comfortable with using PHP to curl a page... but it seems I am lost on filtering the output.

Thanks in advance. :)

  • 写回答

1条回答 默认 最新

  • dtxob80644 2010-04-29 22:28
    关注

    You don't filter output. You use simple_html_dom to parse and manipulate that way. it really is more intuitive.

    Something like

    // Create DOM from URL or file
    $html = file_get_html('...');
    
    // Find all a hrefs in a form tag
    foreach($html->find('form a') as $element)
           echo $element->src . '<br>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog