doz15449 2015-05-26 05:43
浏览 94
已采纳

XPath子串 - 后帮助/查询/评估?

I'm building a php script to transfer selected contents of an xml file to an sql database..

One of the hardcoded XML contents is formatted like this:

<visualURL>
id=18144083|img=http://upload.wikimedia.org/wikipedia/en/8/86/Holyrollernovacaine.jpg
</visualURL>

And I'm looking for a way to just get the contents of the URL (all text after img=).

$Image = $xpath->query("substring-after(/Playlist/PlaylistEntry[1]/visualURL[1]/text(), 'img=')", $element)->item(0)->nodeValue;

Displays a property non-object error on my php output.

There must be another way to just extract the URL contents using XPath that I want, no?

Any help would be greatly appreciated!

EDIT:

Here is the minimum code

<?php

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML('<Playlist>
<PlaylistEntry>
<visualURL>
id=12582194|img=http://upload.wikimedia.org/wikipedia/en/9/96/Sometime_around_midnight.jpg
</visualURL>
</PlaylistEntry>
</Playlist>');
$xpath = new DOMXpath($xmlDoc);
$elements = $xpath->query("/Playlist/PlaylistEntry[1]");

if (!is_null($elements)) 
foreach ($elements as $element) 
$Image = $xpath->query("substring-after(/Playlist/PlaylistEntry[1]/visualURL[1]/text(), 'img=')", $element)-  >item(0)->nodeValue;
print "Finished Item: $Image";

?>

EDIT 2:

After some research I believe I must use $xpath->evaluate instead of my current use of $xpath->query

see this link Same XPath query is working with Google docs but not PHP

I'm not exactly sure how to do this yet.. but i will investigate more in the morning. Again, any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dopt85756 2015-05-27 08:15
    关注

    You're in right direction. Use DOMXPath::evaluate() for xpath expression that doesn't return node(s) like substring-after() (it returns string as documented in the linked page). The following codes prints expected output :

    $xmlDoc = new DOMDocument();
    $xml = <<<XML
    <Playlist>
    <PlaylistEntry>
    <visualURL>
    id=12582194|img=http://upload.wikimedia.org/wikipedia/en/9/96/Sometime_around_midnight.jpg
    </visualURL>
    </PlaylistEntry>
    </Playlist>
    XML;
    
    $xmlDoc->loadXML($xml);
    $xpath = new DOMXpath($xmlDoc);
    $elements = $xpath->query("/Playlist/PlaylistEntry");
    
    foreach ($elements as $element) {
        $Image = $xpath->evaluate("substring-after(visualURL, 'img=')", $element);
        print "Finished Item: $Image <br>";
    }
    

    output :

    Finished Item: http://upload.wikimedia.org/wikipedia/en/9/96/Sometime_around_midnight.jpg 
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘