0

I'm trying to pull out some datas using the DOM Parser technique.

My code :

<?php
// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');

// set error level
$internalErrors = libxml_use_internal_errors(true);

$data = '<div id="show">
                        <ul class="browse_in_widget_col">

                                <li>

                                    <a href="accounting/">
                                        Accounting
                                    </a>
                                    <span>

                                (7420)

                                    </span>
                                </li>
                </div>';

$dom = new DOMDocument();
$dom->loadHTML($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xp = new DOMXPath($dom);
$makes = $xp->query('//ul[@class="browse_in_widget_col"]/ul');
$makeList = [];
foreach ( $makes as $make ) {
    $makeList[] = $make->textContent;
}


print_r($makeList);
?>

Here i want to pull out the between the element <a> tag.

Example here i need Accounting from this element. How i can do that ?

Help me to get all the values in the a tag. Now I'm getting the empty array

1
  • How i can get the values between the a tag. Commented Dec 11, 2019 at 8:30

1 Answer 1

1

In your XPath expression, you are looking for a nested <ul> tag, which there isn't one. If you just want the contents of the <a> tags, you can change the query to //ul[@class="browse_in_widget_col"]//a.

$xp = new DOMXPath($dom);
$makes = $xp->query('//ul[@class="browse_in_widget_col"]//a');
$makeList = [];
foreach ( $makes as $make ) {
    $makeList[] = trim($make->textContent);
}

I've also added trim() to the output to remove any whitespace.

Sign up to request clarification or add additional context in comments.

3 Comments

That can't possibly be the case as it would imply that I didn't either! :-)
Yup thanks it worked. The only mistakes was the //a ?
@VirendraSingh you'll also want to use trim as Nigel did as html textcontent can have a lot of blank space around it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.