Alex Wiebogen Alex Wiebogen - 6 months ago 33
PHP Question

How did i get the ALT Attribute from an image over xpath in php

I try to get some informations from an external page. On some querstions here i found the right way with xpath. After checking the W3C School for the query-syntax i got the first elements without problems.

Now i try to get the value of a ALT - Image Tag and have problems. Here my code and output.

* Created by PhpStorm.
* User: wial
* Date: 25.11.16
* Time: 14:27
ini_set('display_errors', 'On');

$typen = $finder->query('//dl[@class="dl-horizontal"]/dd/ul/li/a/img[@alt]')->item(0);

echo '<pre>' . print_r($typen, true) . '</pre>';

The xpath works, i got the IMG element, but i dont know, how to get the ALT.

my output

DOMElement Object
[tagName] => img
[schemaTypeInfo] =>
[nodeName] => img
[nodeValue] =>
[nodeType] => 1
[parentNode] => (object value omitted)
[childNodes] => (object value omitted)
[firstChild] =>
[lastChild] =>
[previousSibling] =>
[attributes] => (object value omitted)
[ownerDocument] => (object value omitted)
[namespaceURI] =>
[prefix] =>
[localName] => img
[baseURI] => //
[textContent] =>

when i try

$typen = $finder->query('//dl[@class="dl-horizontal"]/dd/ul/li/a/img[@alt]')->item(0)->attributes;

i just got

DOMNamedNodeMap Object
[length] => 2

where i lost the right way?

Br Alex


The DOMElement object has the getAttribute method that you can use in order to get the value of any attribute that DOMElement has:

$typen = $finder->query('//dl[@class="dl-horizontal"]/dd/ul/li/a/img[@alt]')->item(0);