1

I'm trying to obtain the src of a with a specific ID. Example:

<img id="hi_1" src="url of image 1">
<img id="hi_2" src="url of image 2">
<img id="hi_3" src="url of image 3">

result = url of image 1;

I have this code:

$html = file_get_contents('url of site');
preg_match('here I don't know what to do', $html, $src);
$src_out = $src[1];
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
Pau G.P.
  • 11
  • 1
  • 3
  • Possible duplicate of [How do you parse and process HTML/XML in PHP?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – Beck Yang Feb 21 '17 at 12:36

2 Answers2

1

This will solve your problem :)

More information you will find in php documentation.

<?php

    $html = '<img id="hi_1" src="url of image 1">
    <img id="hi_2" src="url of image 2">
    <img id="hi_3" src="url of image 3">';


        $dom = new domDocument();
        $dom->loadHTML($html);
        $dom->preserveWhiteSpace = false;
        $images = $dom->getElementsByTagName('img');
        foreach ($images as $image) {
            $img_id =  $image->getAttribute('id');

            if($img_id == 'hi_2') {
                echo $image->getAttribute('src');

            }
        }
bobomam
  • 58
  • 7
  • Just one thing: When I use $html = file_get_contents(' httpss://www.instagram.com/ '); (for example) this doesn't displays nothing to the screen); Thank you very much for helping me!!! – Pau G.P. Feb 21 '17 at 12:18
  • If you want to load HTML directly form file you need to use http://php.net/manual/en/domdocument.loadhtmlfile.php – bobomam Feb 21 '17 at 12:35
  • I don't understand how to do it, i'm trying to obtain the html form instagram that is HTTPS, the code that you made works perfectly if I use text writted manually. – Pau G.P. Feb 24 '17 at 09:44
  • If you try `file_get_contents('https://www.instagram.com/spacex/media/');` this works perfect. However form some reason I'm not able to get data from main instagram page. Probably they are checking some headers. Try to use CURL instead and pretend that you are desktop or mobile user. BTW if you add parameter ?__a=1 you will get nice JSON response – bobomam Feb 24 '17 at 11:03
0

You're looking for something like <img id="hi_1" src="(.*)">, but regex isn't the right way to go about this. Try using the DOM as per other answers to this question.

Eamonn
  • 418
  • 3
  • 11