问题
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