html - file_get_contents for a specific ( a tag ) from external website URL - PHP

931

I read every single stackoverflow questions and I try each one but nothing works for me.

I have this HTML in the external webpage:

<a href="/gallery/image1.png" id="viewbt">
<div class="view"></div>
</a>

I want to get this whole code using any kind of PHP codes.

468

Answer

Solution:

PHP is server side, while going to a specific HTML tag is a browser feature. There is still a way. You will need to fetch that page and search for the exact tag with regex or with DOM manipulation.

$str = file_get_contents('http://your_php_subpage.com');
// to find the specific tag ( for example the image link )
if(preg_match('#<a href="(.*?)" id="viewbt">.*?</a>#', $str, $m)){
     var_dump($m);
} else {
    echo 'Regex syntax has to be improved to your search criteria'.PHP_EOL;
}

Extra info for regex: http://php.net/preg_match

I suggest regarding a regex tutorial as well, besides the PHP function. You can do a lot more.

People are also looking for solutions to the problem: php - How to write a query that selects 9 rows randomly from database?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.