需要帮助尝试从对象中抓取

时间:2015-11-19 14:59:38

标签: javascript php dom

所以我开始在刮擦的世界里这么好,直到我在我的任务中遇到了巨大的障碍。

所以我不确定它有多可能,但是我试图刮掉一些标记为" THISTEXT"从这段代码。

<div id="mainclass">
<object type="application/x-shockwave-flash" height="400" width="100%" id="live_embed_player_flash" data="http://www.websiteexample.com/channel=THISTEXT" bgcolor="#d7d7d7">
    <param name="allowFullScreen" value="true" />
    <param name="allowScriptAccess" value="always" />
    <param name="allowNetworking" value="all" />
    <param name="movie" value="http://www.websiteexample.com/live_embed_player.swf" />
    <param name="flashvars" value="hostname=www.websiteexample.com&channel=THISTEXT&auto_play=false&start_volume=100" />
</object>

到目前为止,我已设法清除身份证,但这就是我撞墙的地方。能不能帮助我的人会非常感激!

我目前的代码可以在这里找到

function getElementByIdAsString($url, $id, $pretty = true) 
{
    $doc = new DOMDocument();
    @$doc->loadHTMLFile($url);

    if(!$doc) {
        throw new Exception("Failed to load $url");
    }
    $element = $doc->getElementById($id);
    if(!$element) {
        throw new Exception("An element with id $id was not found");
    }
    if($pretty) {
        $doc->formatOutput = true;
    }
    return $doc->saveXML($element);
}
$finalcontent = getElementByIdAsString('http://examplewebsite.com', 'mainclass');
print_r ($finalcontent);

1 个答案:

答案 0 :(得分:0)

我已经重写了你的例子,并添加了一些方法来提取信息 - 它不是很漂亮,但它可以为你提供所需的信息。

$html = ' 
<div id="mainclass">
<object type="application/x-shockwave-flash" height="400" width="100%" id="live_embed_player_flash" data="http://www.websiteexample.com/channel=THISTEXT" bgcolor="#d7d7d7">
    <param name="allowFullScreen" value="true" />
    <param name="allowScriptAccess" value="always" />
    <param name="allowNetworking" value="all" />
    <param name="movie" value="http://www.websiteexample.com/live_embed_player.swf" />
    <param name="flashvars" value="hostname=www.websiteexample.com&channel=THISTEXT&auto_play=false&start_volume=100" />
</object>';

function getElementByIdAsString($html, $id, $pretty = true) {
    $doc = new DOMDocument();
    @$doc->loadHTML($html); // changed this from loadHTMLFile() 

    if(!$doc) {
        throw new Exception("Failed to load $url");
    }
    $element = $doc->getElementById($id);
    if(!$element) {
        throw new Exception("An element with id $id was not found");
    }

    // get all object tags
    $objects = $element->getElementsByTagName('object'); // return node list

    // take the the value of the data attribute from the first object tag
    $data = $objects->item(0)->getAttributeNode('data')->value;

    // cut away the unnecessary parts and return the info
    return substr($data, strpos($data, '=')+1);

}

// call it:
$finalcontent = getElementByIdAsString($html, 'mainclass');

print_r ($finalcontent);

在这个例子中,我使用的是html字符串,而不是像你这样的文件。实施时请考虑这一点。

真诚地

相关问题