我的问题是,我有一个XML内容。我用PHP SimpleXMLElements()类阅读它。 XML看起来像这样:
<search_result>
<movies>
<movie>
<title>Rambo 1</title>
</movie>
<movie>
<title>Terminator 1</title>
</movie>
<movie>
<title>Romeo and Juliett</title>
</movie>
</movies>
<program>
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Doku-cinema</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Romantic-Romeo and Juliett</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Doku-cinema</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
</program>
我想找到包含示例'Rome'的所有节点并仅返回节点。 我的意思是...... exmaple:
$xml = simplexml_load_file("moviecinemas.xml");
$searchNodes = $xml->xpath('//*[contains(.,'Romeo')]');
我想得到这个结构:
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Romantic-Romeo and Juliett</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
<movie>
<title>Romeo and Juliett</title>
</movie>
我不知道怎么可能,是的。
答案 0 :(得分:1)
对于我所看到的,你只有一点XPath问题。顺便说一下,在您的问题中,示例XML格式不正确,它没有 search_result 节点关闭标记。
这是一个有效的例子:
<?php
$xml = <<<XML
<search_result>
<movies>
<movie>
<title>Rambo 1</title>
</movie>
<movie>
<title>Terminator 1</title>
</movie>
<movie>
<title>Romeo and Juliett</title>
</movie>
</movies>
<program>
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Doku-cinema</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Romantic-Romeo and Juliett</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
<item>
<id>5405059</id>
<show_date>03.22.</show_date>
<show_time>14:30</show_time>
<rfcdate>Fri, 22 Mar 2013 14:30:00 +0100</rfcdate>
<title>Doku-cinema</title>
<genre/>
<channel_name>d1 Tv</channel_name>
<channel_id>232</channel_id>
</item>
</program>
</search_result>
XML;
$sxe = new SimpleXMLElement($xml);
$romeoItems = $sxe->xpath('//program/item[contains(./title, "Romeo")]');
print_r($romeoItems);
<强>输出:强>
Array
(
[0] => SimpleXMLElement Object
(
[id] => 5405059
[show_date] => 03.22.
[show_time] => 14:30
[rfcdate] => Fri, 22 Mar 2013 14:30:00 +0100
[title] => Romantic-Romeo and Juliett
[genre] => SimpleXMLElement Object
(
)
[channel_name] => d1 Tv
[channel_id] => 232
)
)