if else statement
I am parsing text from an xml file that always reads "There are no new codes." At least once a day this text will change to something different. My goal here is to return the new text when it changes, and do nothing when it reads "There are no new codes.". My problem is that it always returns "There are no new codes."
//get source of remote site
$source = file_get_contents('http://someurl.com');
//match strings
preg_match('#<code>(.*?)</code>#', $source, $match);
//if match is equal to "There are 开发者_如何学编程no new codes." do nothing else return new match
if ( $match[0] == "There are no new codes." ) {
/* Do Nothing */;
} else {
echo $match_one[0];
}
You have two problems here.
First, in the regex #<code>(.*?)</code>#'
, the 0th match (index in the array) is the entire string, while the 1st match (index) will be the contents of the parens. Therefore, use $match[1]
.
Your second problem is that you're getting XML, but aren't using any of PHP's XML functions. You can't safely parse XML with regular expressions. Try the DOM on for size.
$doc = new DOMDocument();
$doc->load($url);
$code_tags = $doc->getElementsByTagName('code');
echo $code_tags->item(0)->textContent;
I believe you want to look at $match[1]
not $match[0]
. $match[0]
returns the text matching the full pattern (the code tags and all).
精彩评论