Pretty simple i'm sure, but..
I've got a file that is guaranteed to have only an <h1>some text</h1> and a <p>some more text</p> in it.
How would i go about returning these to elements as separate variables?
If your file is an HTML one, the general solution would be to :
DOMDocument, with
DOMDocument::loadHTML if you have your HTML content as a stringDOMDocument::loadHTMLFileDOMDocument::getElementsByTagName should be perfectYour file is just text, so you're going to have to parse it. Generally HTML isn't all that suitable for parsing with normal operations, but if you know the exact contents you shouldn't have a problem.
Depending on what your separator is between the two tag blocks (let's pretend it's a \n, you could do something like this:
$contents = file_get_contents("yourfile.html");
list($h1,$p) = explode("\n",$contents);
That would give you the two text blocks in $h1 and $p. You could parse the rest from there if you needed to do more work.
</h1> tag from the variable contents. I guess it depends on whether he wants the HTML tags as part of his variable content or not.You can use something like this:
function strBetween($au, $au2, $text) {//gets substring beetween $au and $au2 in $text
$pau = strpos($text, $au);
if($au2 !== '') {
$pau2 = strpos($text, $au2,$pau);
if($pau !== false && $pau2 !== false)
return substr($text, $pau+strlen($au), $pau2-$pau-strlen($au));
else
return '';
} else {
return substr($text, $pau+strlen($au));
}
}
$contents = file_get_contents("yourfile.html");
$h1 = strBetween('<h1>', '</h1>', $contents);
$p = strBetween('<p>', '</p>', $contents);