How can i parse what i want with this HTML code?

Viewed 78

I would like to extract the attributes "href" and "title" from this HTML code :

<span class='ipsType_break ipsContained'>
  <a 
    href='https://www.xxxx/topic/11604/' 
    class='' title='[2002] Le Boulet [xxxx] '
    data-ipsHover data-ipsHover-target='https://www.xxxxx/topic/1160'
    data-ipsHover-timeout='1.5'>
<span>[2002] Le Boulet [xxxxx]</span>
  </a>
</span>

I tried some codes in PHP but it's not working :(

By example

$e = $html->find('span[class=ipsType_break ipsContained]');
$value = $e->title;
print_r($value);
3 Answers

You can use a single call using find, but you have to indicate that you are looking for an anchor a, as the span here does not have a title attribute.

As find returns an array, you have to indicate that you want the first element by specifying 0 as the second argument.

$e = $html->find('span[class=ipsType_break ipsContained] a', 0);
echo $e->href . PHP_EOL;
echo $e->title;

Output

https://www.xxxx/topic/11604/
[2002] Le Boulet [xxxx]

If you want to find an HTML element using its classes, you can use the dot notation like in CSS:

$e = $html->find('span.ipsType_break.ipsContained');

You actually want those attributes form the a elements inside the span. You are correctly finding the span tags but the statement you use returns an array of elements which you need the first one only. Then you should search children of this span tag to extract its first a child (again, because find returns an array of elements event if there is only one element matching your selector):

$a = $html->find('span[class=ipsType_break ipsContained]', 0)->find('a', 0);
print_r (['title' => $a->title, 'href' => $a->href]);

the output is:

Array
(
    [title] => [2002] Le Boulet [xxxx] 
    [href] => https://www.xxxx/topic/11604/
)
Related