XPath not returning values with quotes
<html>
<body>
<channel>
<item>
<link>"http://www.example.com/"
</link>
<title>This is a title
</title>
</item>
<item>
<link>"http://www.example2.com/"
</link>
<title>This a 2nd title
</title>
</item>
</channel>
</body>
</html>
$query = '/html/body/channel/item/title';
$xpath->query($query);
$i = 0;
foreach ( $xpath->query($query) as $key )
{
echo '<p>'.$xpath->query($query) -> item($i) -> nodeValue . '</p><br />';
$i++;
}
I tried the following queries:
$query = '/html/body/channel/item/link';开发者_JAVA百科
and
$query = '/html/body/channel/item/link/text()';
I can return <item>
and <title>
just fine. Just not <link>
. Is there something I'm missing?
Your code is broken and does not make sense
1 $query = '/html/body/channel/item/title';
2 $xpath->query($query);
3 $i = 0;
4 foreach ($xpath->query($query) as $key)
5 {
6 echo '<p>'.$xpath->query($query) -> item($i) -> nodeValue . '</p><br />';
7 $i++;
8 }
will query for title elements (2) but since the result isn't assigned, it is superfluous. Then you do foreach and query again (4). This time you assign each title DOMElement to $key (which is bad wording imo). In the foreach, you do yet another query for title elements (6) and fetch the items/title elements in it from your counter variable (3/6). That is superfluous as well, because you already have that element in $key (3). So you are doing three identical queries where you just need one and you do a foreach without using it.
It should be
foreach ($xpath->query('/html/body/channel/item/title') as $titleElement) {
printf('<p>%s</p>', $titleElement->nodeValue);
}
Since you are already using DOM to work with the markup, you could also create the p element with it instead of using string concatenation, e.g.
foreach ($xpath->query('/html/body/channel/item/title') as $titleElement) {
echo $domDocument->saveXml(
$domDocument->createElement('p', $titleElement->nodeValue)
);
}
If you want the link elements, change the XPath accordingly to query for that instead of title. The quotes in the node value have nothing to do with it at all. They will show just fine.
Full working example showing how to combine <title>
and <link>
elements into <a>
elements
精彩评论