开发者

php return elements from file content

开发者 https://www.devze.com 2022-12-28 04:57 出处:网络
Pr开发者_JAVA百科etty 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.

Pr开发者_JAVA百科etty 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 :

  • Load it to a DOMDocument, with
    • DOMDocument::loadHTML if you have your HTML content as a string
    • or DOMDocument::loadHTMLFile
  • Use DOM methods to access your nodes
    • Here, DOMDocument::getElementsByTagName should be perfect
  • ANd, then, once you have your node, work's done ;-)
    • Not : if your HTML elements contain sub-elements, and you want the whole content, including sub-tags, as a string, take a look at, for example, this user note


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消