Question

I'm working on my php to get the id of href tags using with DOMDocument.

I'm trying to parse the element with id called <a id="test. When I tried to parse the id, I will get the empty return.

I'm using this:

$domdoc = new DOMDocument();
$domdoc->strictErrorChecking = false;
$domdoc->recover=true;
//@$domdoc->loadHTMLFile($baseUrl);
@$domdoc->loadHTML($baseUrl);

$links = $domdoc->getElementsByTagName('test');
$data = array();
foreach($links as $link)
{
  echo $link;;
}

Here is the output:

echo '<a id="test" href="http://www.mysite.com/script.php?=' . $row["channels"] . "&id=" . $row["id"] . '">http://www.mysite.com/script.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '</a>

Does anyone know how I can get the element with id called <a id="test?

Edit: Here is the update code:

<?php
ini_set('max_execution_time', 300);
$errmsg_arr = array();
$errflag = false;

$xml .= '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '
<tv generator-info-name="www.mysite.com/xmltv">';

$baseUrl = file_get_contents('http://www.mysite.com/get-listing.php');

$domdoc = new DOMDocument();
$domdoc->strictErrorChecking = false;
$domdoc->recover=true;
//@$domdoc->loadHTMLFile($baseUrl);
@$domdoc->loadHTML($baseUrl);

//$links = $domdoc->getElementsByTagName('test');
//$links = $domdoc->getElementById('test');
$links = $domdoc->getElementsByTagName('a');

$data = array();
foreach($links as $link)
{

  echo $domdoc->saveXML($link);
}
Was it helpful?

Solution

I think you're using the getElementsByTagName() the wrong way. This method is used to get HTML tags, not their attributes or value of attributes.

Please check the following example:

<?php
$html = '<a id="test" href="#">Some link text here</a>';
$html .= '<a id="test2" href="#">Some link text here</a>';
$DOM = new DOMDocument();
$DOM->loadHTML($html);

$links = $DOM->getElementsByTagName('a');
foreach($links as $link) {
    if( $link->getAttribute('id') == "test" ) {
        echo "<h4>Element with id test Found!</h4>";
        // Or do something else here when you find the element by id="test"
            // As an example for what you're trying from my understanding
            echo $DOM->saveHTML($link);
            // This will echo the node as html back to the browser
    }
}
?>

I used two <a> tags as my HTML input, and searched for the one that has an attribute of id with the value "test".

OTHER TIPS

Update your code.. Work for my :)

<?php
$html = file_get_contents('http://www.serbalucu.com');
$dom = new DOMDocument;
@$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');

foreach($links as $link) {

    if( $link->getAttribute('class') == "with-ul" ) {
        echo "<h1>RESULT FOUND</h1>";

            echo $dom->saveHTML($link);
    }

}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top