Alex Wiebogen Alex Wiebogen - 10 months ago 49
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.

<?php
/**
* Created by PhpStorm.
* User: wial
* Date: 25.11.16
* Time: 14:27
*/
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$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] => //www.example.de/
[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

Answer Source

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);

var_dump($typen->getAttribute('alt'));