0

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.

4
  • 1
    have you tried this? //div[@id='post']/ul/li[2] what's the criteria of "Target content"? Commented Jun 27, 2019 at 2:58
  • I think we have only option to get it with array Commented Jun 27, 2019 at 5:05
  • The html you posted is invalid as it has multiple div's with id "post". Commented Jun 27, 2019 at 6:13
  • "I think we have only option to get it with array"....that doesn't stop you from using a more precise xPath query as per the suggestion. But yes you will have another problem because it may not like the invalid duplicate IDs Commented Jun 27, 2019 at 6:21

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.