1

Here is my code:

$res = file_get_contents("http://www.lenzor.com/photo/search/index/type/user/%D8%B9%D9%84%DB%8C//text/%D9%81%D8%A7%D8%B7%D9%85%D9%87");

$doc = new \DOMDocument();
@$doc->loadHTMLFile($res);
$xpath = new \DOMXpath($doc);
$links = $xpath->query("//ul[@class='user_box']/li");
$result = array();
if (!is_null($links)) {
    foreach ($links as $link) {
        $href = $link->getAttribute('class');
        $result[] = [$href];
    }
}

print_r($result);

Here is the content I'm working on. I mean it's the result of echo $res.


Ok well, the result of my code is an empty array. So $links is empty and that foreach won't be executed. Why? Why //ul[@class='user_box']/li query doesn't match the DOM ?

Expected result is an array contains the class attribute of lis.

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89

1 Answers1

1

Try this, Hope this will be helpful. There are few mistakes in your code.

1. You should search like this '//ul[@class="user_box clearfix"]/li' because class="user_box clearfix" class attribute of that HTML source contains two classes.

2. You should use loadHTMLinstead of loadHTMLFile.

<?php
ini_set('display_errors', 1);

libxml_use_internal_errors(true);
$res = file_get_contents("http://www.lenzor.com/photo/search/index/type/user/%D8%B9%D9%84%DB%8C//text/%D9%81%D8%A7%D8%B7%D9%85%D9%87");

$doc = new \DOMDocument();
$doc->loadHTML($res);
$xpath = new \DOMXpath($doc);
$links = $xpath->query('//ul[@class="user_box clearfix"]/li');
$result = array();
if (!is_null($links)) {
    foreach ($links as $link) {
        $href = $link->getAttribute('class');
        $result[] = [$href];
    }
}

print_r($result);
Community
  • 1
  • 1
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42