mdskinner
mdskinner

Reputation: 498

php return elements from file content

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?

Upvotes: 0

Views: 101

Answers (3)

user327485
user327485

Reputation: 1

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);

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

If your file is an HTML one, the general solution would be to :

Upvotes: 2

zombat
zombat

Reputation: 94237

Your 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.

Upvotes: 1

Related Questions