【问题标题】:How to divide text from a function如何从函数中分割文本
【发布时间】:2017-08-06 09:08:26
【问题描述】:

我构建了这个函数来从一个 html 页面获取 h1 标签:

//$html = file_get_html('https://www.sports-reference.com/olympics/summer/1896/');
//echo $html;

function getTextBetweenTags($url, $tagname) {
    $values = array();
    $html = file_get_html($url);
    foreach($html->find($tagname) as $tag) {
        $values[] = trim($tag->innertext);
    }

    return $values;
}

$output = getTextBetweenTags('https://www.sports-reference.com/olympics/summer/1896/', 'h1');
echo '<pre>';
print_r($output);

作为输出我得到:

Array
(
    [0] => 1896 Athina Summer Games
)

是否可以代替:

Array
    (
        [0] => 1896
        [1] => Athina
        [2] => Summer
    )

很好接受的其他解决方案,因为我确定 h1 标签是页面中唯一的标签,所以我不需要从 html 中查找所有 h1 标签

【问题讨论】:

标签: php


【解决方案1】:

希望这会有所帮助

解决方案 1:(而不是 return $values; 你应该返回这个)

$result=explode(" ",$values[0]);
array_pop($result);
return $result;

这里我们使用DOMDocument 来实现所需的输出

解决方案 2:

ini_set('display_errors', 1);
function getTextBetweenTags($url, $tagname)
{
    libxml_use_internal_errors(true);
    $domDocument = new DOMDocument();
    $domDocument->loadHTMLFile($url);

    $domXPath = new DOMXPath($domDocument);
    $results = $domXPath->query("//$tagname");//querying tag
    return explode(" ", $results->item(0)->textContent);//getting content of first tag and exploding it on space
}
$output = getTextBetweenTags('https://www.sports-reference.com/olympics/summer/1896/', 'h1');
array_pop($output);
print_r($output);

输出:

Array
(
    [0] => 1896
    [1] => Athina
    [2] => Summer
)

【讨论】:

    猜你喜欢
    • 2022-10-21
    • 2013-11-09
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2010-10-31
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多