Teddy13
Teddy13

Reputation: 3854

parsing xml id from website xml parser php

I would like to parse the following id: date

How would I select it? I know how to select a class but I have had no luck for an id.

This is what I did with classes:

$xml->xpath('//*[@class="date"]'); 

I tried switching @class for @id but no luck. What am I doing wrong?

Thank you in advance

@$doc=new DOMDocument();
@$doc->loadHTML($html5);

$xml=simplexml_import_dom($doc);
$images=$xml->xpath('//*[@id="date"]'); 
$arr= array();
foreach ($images as $img) {
  $arr[]= $img;
}

echo $arr[0];

Upvotes: 1

Views: 323

Answers (1)

user895378
user895378

Reputation:

Now that you made me feel bad ...

The xpath query below will retrieve all elements that have the attribute id = date. Since you only care about the first one (there shouldn't be more than one because ID attributes are supposed to be unique ... but you never know), you need to reference item(0) in the DOMNodeList returned by the xpath query.

$xml = '<root><p>element we don\'t care about</p><p id="date">date element text</p></root>';
$doc = new DomDocument;
$doc->loadXML($xml);

$xpath = new DOMXPath($doc);
if ($el = $xpath->query("//*[@id='date']")->item(0)) {
  echo $el->nodeValue; // outputs: date element text
} else {
  echo 'no elements exist in the xml with an "id" attribute';
}

Hope that helps.

Upvotes: 2

Related Questions