PHP how to set color to certain keywords (text) in scraped data

坚强是说给别人听的谎言 提交于 2019-12-14 04:10:33

问题


Trying to do something a bit tricky, where I set a color for given keywords for an echo, that is gathered from web scraping. I was given an answer once, but unable to get it to actually change any colors. Here's the code I'm working with.

 <?php 

$doc = new DOMDocument;

// djia/nas/sp current values
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);

foreach ($entries as $entry) {
echo trim($entry->textContent);  // use `trim` to eliminate spaces

}

?>

It's spitting out this result: DJIA 21271.97 +89.44(0.42%)NASDAQ 6207.92 -113.85(-1.80%)S&P 500 2431.77 -2.02(-0.08%)

How could I format it to always color the word for ex, DJIA, as red? I understand the logic of what would have to happen, but not sure how to make it work with my existing code.

I was supplied with this as an answer once, but again it didn't actually change the color of "DJIA." Perhaps someone out there knows what I was doing wrong possibly? *Remember this is scraped text I'm dealing with here.

<?php 

$doc = new DOMDocument;

// djia/nas/sp current values
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    if(trim($entry->textContent) =='DJIA'){//compare with the word you want 
to make red
 echo "<span style='color:red;'>". trim($entry->textContent) ."
</span>";
    }else{
        echo trim($entry->textContent);
    }
 }

?>

Thanks for any feedback!!


回答1:


strreplace('DJIA', '<span class="color:red">DJIA</span>', $someText);?



来源:https://stackoverflow.com/questions/44512373/php-how-to-set-color-to-certain-keywords-text-in-scraped-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!