根据一段deeplink属性选择一个xml对象

时间:2014-06-13 14:23:39

标签: php xml xml-parsing simplexml filtering

我正在使用xml文件开发页面以在屏幕上打印。现在我需要只打印具有url起始部分的对象到这样的属性:

<product zupid="d490dd40f6dbaf238f28b57abad92fbf">
     <deepLink>http://ad.zanox.com/ppc/?28132512C86846042&amp;ULP=[[offerte-viaggi/vacanze/sconti-triton-villas-residence-hotel-calabria.html]]</deepLink>
</product>

现在我正在解析所有因为我使用这个函数:

for ($i=$offset; $i<$limit+$offset; $i++) { 
     $article=$xml->product[$i];
     $link = $article->deepLink;

     echo "<a target='_blank' href='$link'>Go to link</a>";
}

如何只选择具有属性/网址部分的对象?

1 个答案:

答案 0 :(得分:0)

SimpleXMLElement :: xpath()方法允许您使用xpath表达式来获取元素数组:

$documentElement = simplexml_load_string($xml);

$offset = 1;
$count = 2;

$expression = '//product
  [starts-with(deepLink, "http://ad.zanox.com/")]
  [position() >= '.$offset.' and position() < '.($offset + $count).']
';

foreach ($documentElement->xpath($expression) as $product) {
  var_dump((string)$product->deepLink);
}

演示:https://eval.in/162300

关于表达:

选择骰子文件中的所有product元素......

//product

...如果作为文本的deepLink元素以给定字符串

开头

//product [starts-with(deepLink, "http://ad.zanox.com/")]

使用最小值和最大值

限制找到的节点列表

//product [starts-with(deepLink, "http://ad.zanox.com/")] [position() >= 1 and position() < 3]`

提示:Xpath中的位置以1开头,而不是0。

相关问题