2

i get the html from another site with file_get_contens, my question is how can i get a specific tag value?

let's say i have:

<div id="global"><p class="paragraph">1800</p></div>

how can i get paragraph's value? thanks

1
  • 1
    It should be file_get_contents(). Commented Apr 22, 2010 at 14:46

4 Answers 4

4

If the example is really that trivial you could just use a regular expression. For generic HTML parsing though, PHP has DOM support:

$dom = new domDocument();
$dom->loadHTML("<div id=\"global\"><p class=\"paragraph\">1800</p></div>");
echo $dom->getElementsByTagName('p')->item(0)->nodeValue;
Sign up to request clarification or add additional context in comments.

2 Comments

and if i want to get elements by class name?
I don't think there's a method for that, DOMs usually don't have it, you need to loop over the nodes and check each one. php.net/manual/en/class.domdocument.php
3

You need to parse the HTML. There are several ways to do this, including using PHP's XML parsing functions.

However, if it is just a simple value (as you asked above) I would use the following simple code:

// your content
$contents='<div id="global"><p class="paragraph">1800</p></div>';

// define start and end position
$start='<div id="global"><p class="paragraph">';
$end='</p></div>';

// find the stuff
$contents=substr($contents,strpos($contents,$start)+strlen($start));
$contents=substr($contents,0,strpos($contents,$end));

// write output
echo $contents;

Best of luck!

Christian Sciberras

(tested and works)

1 Comment

I would recommend using Michael Mrozek's answer if you want more flexibility. However, I would discourage the use of RegExp especially in this context: [1] They are slower compared to simple traditional methods. [2] They are harder to maintain. [3] They imply you knowing them which is probably not something you would want to spend a lot of time on.
0
$input  = '<div id="global"><p class="paragraph">1800</p></div>';
$output = strip_tags($input);

2 Comments

He wants to use file_get_contents() and that example he gave was what could be found in the example website.
I know. But what if his website has only one <div> with one value ? :)
0
preg_match_all('#paragraph">(.*?)<#is', $input, $output);

print_r($output);

Untested.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.