Swapnil Rajja
Swapnil Rajja

Reputation: 107

How to get specific value in PHP from external URL

I am trying to get specific value from an external URL. Somehow I'm stuck now. Please somebody see and help.

I am trying to do this with new DOMDocument();

<?php
    $html = file_get_contents('https://someurl.com');
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);

    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom);

    $elements = $xpath->query("//div[@id='post']");
    $maindata = $elements[1];


    echo $maindata->nodeValue;
?>

Now see the structure of HTML file on target URL

<div id="post" align="left">
    <ul>
        <li>
            <a>some content</a>
        </li>
    </ul>
</div>

<div id="post" align="left">
    <ul>
        <li>
            <a>some content</a>
        </li>
        <li>
            <a>Targeted Content</a>
        </li>
    </ul>
</div>

<div id="post" align="left">
    <ul>
        <li>
            <a>some content</a>
        </li>
    </ul>
</div>

When I tried to get this from an array, it gave me the entire div value (some content Targeted content). I need only targeted content.

Upvotes: 0

Views: 83

Answers (1)

Bram Verstraten
Bram Verstraten

Reputation: 1557

Try the following:

<?php
$html = file_get_contents('https://someurl.com');
$dom = new DOMDocument();
libxml_use_internal_errors(true);

$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$elements = $xpath->query("//div[@id='post']/ul/li[2]/a");
$values = [];
foreach ($elements as $element) {
    $values[] = $element->textContent;
}

print_r($values);

Upvotes: 1

Related Questions