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

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

报告相同问题?