Not sure I understand the question correctly, but the second XPath expression already does what you are describing. It does not match against the text node of the A element, but the href attribute:
点击(此处)折叠或打开
- $html = <<< HTML
- <ul>
- <li>
- <a href="">Description</a>
- </li>
- <li>
- <a href="">Description</a>
- </li>
- </ul>
- HTML;
- $xml = simplexml_load_string($html);
- $list = $xml->xpath("//a[contains(@href,'foo')]");
Outputs:
点击(此处)折叠或打开
- array(1) {
- [0]=>
- object(SimpleXMLElement)#2 (2) {
- ["@attributes"]=>
- array(1) {
- ["href"]=>
- string(31) ""
- }
- [0]=>
- string(11) "Description"
- }
- }
As you can see, the returned NodeList contains only the A element with href containing foo (which I understand is what you are looking for). It contans the entire element, because the XPath translates to Fetch all A elements with href attribute containing foo. You would then access the attribute with
点击(此处)折叠或打开
- echo $list[0]['href'] // gives ""
If you only want to return the attribute itself, you'd have to do
点击(此处)折叠或打开
- //a[contains(@href,'foo')]/@href
Note that in SimpleXml, this would return a SimpleXml element though:
点击(此处)折叠或打开
- array(1) {
- [0]=>
- object(SimpleXMLElement)#3 (1) {
- ["@attributes"]=>
- array(1) {
- ["href"]=>
- string(31) ""
- }
- }
- }
but you can output the URL now by
点击(此处)折叠或打开
- echo $list[0] // gives ""