1

我正在尝试option从 ppa 添加标签,以便在我自己的网站上显示它支持的当前 Ubuntu 发行版。

这就是我到目前为止所拥有的。

<?php include 'https://launchpad.net/~gregory-hainaut/+archive/pcsx2.official.ppa#field.series'; ?>

这是option标签的内容:

<select onchange="updateSeries(this);" size="1" name="field.series" id="field.series">
<option value="YOUR_UBUNTU_VERSION_HERE" selected="selected">Choose your Ubuntu version</option>
<option value="trusty">Trusty (14.04)</option>
<option value="saucy">Saucy (13.10)</option>
<option value="raring">Raring (13.04)</option>
<option value="quantal">Quantal (12.10)</option>
<option value="precise">Precise (12.04)</option>
<option value="lucid">Lucid (10.04)</option>
</select>
4

1 回答 1

2

您将希望使用file_get_contents(or curl) 获取实际的源代码,并使用 (for instance) 对其进行解析DOMDocument。例如,您可以尝试这样的事情:

Fist 定义一个函数,让我们获取节点的 innerHTML(感谢Hiam):

function DOMinnerHTML(DOMNode $element) 
    { 
        $innerHTML = ""; 
        $children  = $element->childNodes;

        foreach ($children as $child) 
        { 
            $innerHTML .= $element->ownerDocument->saveHTML($child);
        }

        return $innerHTML; 
    } 

然后获取内容并通过ID抓取选择菜单

$ppa = file_get_contents('https://launchpad.net/~gregory-hainaut/+archive/pcsx2.official.ppa#field.series');

$doc = new DomDocument;
$doc->loadHTML($ppa);
$innerHTML = DOMinnerHTML($doc->getElementById('field.series_filter'));

如果我回$innerHTML显结果是:

<option value="">Any series</option>
<option value="trusty">Trusty</option>
<option value="saucy">Saucy</option>
<option value="raring">Raring</option>
<option value="quantal">Quantal</option>
<option value="precise">Precise</option>
<option value="lucid">Lucid</option>

从该结果中,您会注意到我只获得了选择菜单的内部 html,因此您需要将返回的 innerHTML 包装在一个select标记中:

<select name='[your name]' [...other properties]>
<?=$innerHTML;?>
</select>

编辑

OP 在评论中提到一切正常,但他想要一个与上面选择的不同的选择菜单。因为他正在抓取的页面具有无效标记(两个单独select的菜单具有相同的id),所以DOMDocument getElementById调用未获取正确的节点。要纠正这个问题,您必须查看 DOM 树并细化一个唯一的父元素,以便您可以首先获取父节点,然后运行查询以找到您要查找的项目。在这种情况下,OP 想要的菜单位于 ID 为 "" 的 a 内部div,所以我们所做的就是抓取该节点,然后使用它getElementsByTagName来抓取选择菜单:

//... get the code (set in $ppa) as per the original section
$doc->loadHTML($ppa);

//Grab the parent div because it has a unique ID
$parent_div = $doc->getElementById('series-widget-div');
//then seach for all <select> tags and grab the first one
$select_menu = $parent_div->getElementsByTagName('select')->item(0);
//... and now we're ready to get the innerHTML
$innerHTML = DOMinnerHTML( $select_menu );
//echo it out!
echo $innerHTML;
于 2014-01-26T17:58:52.673 回答