PHP 数组仅使用“获取元标记”函数的第一行文本区域


PHP array only using the first line of text area for 'Get Meta Tags' Function

我对PHP相当陌生,所以请耐心等待:)

如果将URL放入文本区域,然后为每个URL提取元数据,我正在尝试做什么。

我已经制作了脚本,但是当我在文本区域中放置多个URL时,它只返回最后一个输入URL的数据,我想也许你们可以帮助我:)

<form method="POST">
<textarea name="TAData">
</textarea>
<input type="submit" value="submit"/>
</form>
<div id="checkboxes">
<input type="checkbox" name="vehicle" value="PR" /> Show me the PR<br />
<input type="checkbox" name="vehicle" value="KW Tag" /> Show me the KW tag<br />
<input type="checkbox" name="vehicle" value="Title Tag" /> Show me the Title tag<br />
</div>
<div id="checkboxes">
<input type="checkbox" name="vehicle" value="1stH1" /> Show me the 1st H1<br />
<input type="checkbox" name="vehicle" value="2ndH1" /> Show me the 2nd H1 tag<br />
<input type="checkbox" name="vehicle" value="SeedKW" /> Show me Seed KW's<br />
</div>
<div id="nofloat"></div>
<?php
//make the array 
$TAarray = explode("'n", strip_tags($_POST['TAData'])); 
foreach ($TAarray as $key => &$line) { $line = trim($line); }
            // get the meta data for each url
            $tags = get_meta_tags($line);
unset($tags["content-type"]);
unset($tags["page-type"]);
unset($tags["page-topic"]);
unset($tags["audience"]);
unset($tags["content-language"]);       
            echo '<tr>';
            foreach ($tags as $meta)        
            {
                    echo '<td>' . $meta . '</td>';
            }
            echo '</tr>';
?>

行上使用修剪的位置之后的结束 } 表示 foreach 结束,并且在循环之后只有最后一行可用于其他操作。只需将该括号移到末尾即可。

如果将

foreach与引用一起使用,则最好在循环后删除该引用:

foreach ($TAarray as $key => &$line)
{
    $line = trim($line); 
}
unset($line); # remove the reference for safety reasons

但是,由于您不会在该代码之后迭代$TAarray,因此该代码无论如何都是多余的。不要编写多余的代码。我建议如下:

//make the array 
$TAarray = explode("'n", strip_tags($_POST['TAData'])); 
$TAarray = array_map('trim', $TAarray);

我建议你把它放到它自己的函数中:

/**
 * @param string $html
 * @return string[] lines
 */
function getTrimmedTextLinesArrayFromHTMLBlock($html)
{
    $text = strip_tags($html);
    $lines = explode("'n", $text);
    $trimmed = array_map('trim', $lines);
    return $trimmed;
}

然后,您可以在任何您认为合适的地方使用它。您还可以使用不同的输入独立测试此函数:

$lines = getTrimmedTextLinesArrayFromHTMLBlock($_POST['TAData']));
$blacklist= array("content-type", "page-type", "page-topic", 
                "audience", "content-language");
foreach ($lines as $line)
{
    if (! $tags = get_meta_tags($line)) continue;
    echo '<tr>';
    foreach ($tags as $key => $meta)
    {
        if (in_array($key, $blacklist)) continue;
        echo '<td>' . $meta . '</td>';
    }
    echo '</tr>';
}

我希望这是有帮助的。