<\/script>')

PHP Xpath: get all href containing letter "

Say I have an html file that I downloaded, I run this request:

$url = 'http://www.fangraphs.com/players.aspx';
$html = file_get_contents($url);    
$myDom = new DOMDocument;
$myDom->formatOutput = true;
@$myDom->loadHTML($html);
$anchor = $xpath->query('//a[contains(@href,"letter")]');

This gives me a list of these anchors that look like this:

<a href="players.aspx?letter=Aa">Aa</a>

But I need a way to get only "players.aspx? Letter = Aa".

I thought I could try:

$anchor = $xpath->query('//a[contains(@href,"letter")]/@href');

But this gives me a php error saying that I could not add node when I try the following:

$xpath = new DOMXPath($myDom);
$newDom = new DOMDocument;
$j = 0;
while( $myAnchor = $anchor->item($j++) ){
   $node = $newDom->importNode( $myAnchor, true );    // import node
   $newDom->appendChild($node);
}

Any idea how to get only the href tag value that the first request selects? Thank!

+5
source share
3 answers

XPath (.. DOMAttr), (.. DOMElement ). , , , . A DOMAttr node ; a DOMElement, . , DOMAttr .

W3C:

Attr Node, , DOM .,, DOM , , ,

DOMAttr DOMElement , DOMAttr .

, DOMText node . , :

    $newDom->appendChild($node);

:

    $newDom->appendChild(new DOMText($node->value));
0

//a/@href[contains(., 'letter')]

href a, () "letter".

+3

try it.

$xml_string = 'your xml string';
$xml = simplexml_load_string($xml_string);
foreach($xml->a[0]->attributes() as $href => $value) {
    $myAnchorsValues[] = $value;
}

var_dump($myAnchorsValues);
0
source

All Articles