这是xml文件:
<item>
<title>TITLE</title>
<link>
http://www.website.com/#!/1234
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">**this is what I need**</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
</item> <item>
<title>TITLE</title>
<link>
http://www.website.com/#!/0987
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">this is what I don't need</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
</item>
如何获取g:id的值,其中link为http://www.website.com/#!/1234
谢谢!
这是我用来捕捉的代码:
$xml = new SimpleXMLElement($link);
foreach ($xml as $value){
if($value['link']=="http://www.website.com/#!/1234"){
echo $value['g:id'];
}
}
答案 0 :(得分:1)
下一代码搜索g:id
的值link
是“http://www.website.com/#!/1234”(当找到值时显示):
<?php
$data = <<<BLOCK
<item>
<title>TITLE</title>
<link>
http://www.website.com/#!/1234
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">**this is what I need**</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
<item> </item>
<title>TITLE</title>
<link>
http://www.website.com/#!/0987
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">this is what I don't need</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
</item>
BLOCK;
$parser = xml_parser_create();
xml_parse_into_struct( $parser, $data, $vals, $index );
xml_parser_free( $parser );
$next = false; // THIS VARIABLE IS VERY IMPORTANT. THE FOREACH VISITS EACH
// TAG, ONE BY ONE, SO, WHEN THE "LINK" TAG IS READ, IT'S
// NECESSARY TO WAIT FOR THE NEXT LOOP OF THE FOREACH. WHEN
// $NEXT==TRUE, MEANS THAT "http://www.website.com/#!/1234"
// WAS FOUND, SO THE TAG "G:ID" IS THE ONE WE ARE LOOKING FOR.
foreach ( $vals as $item ) // VISIT EACH TAG IN XML DATA (TITLE,LINK,G:ID,...)
{ // CHECK IF CURRENT TAG'S VALUE IS "http://www.website.com/#!/1234".
// STR_REPLACE IS USED BECAUSE "LINK" TAG TAKES THREE LINES AND ITS VALUE
// CONTAINS LINE BREAKS.
if ( strcasecmp( str_replace( array("\r","\n"),'',$item[ "value" ] ),
"http://www.website.com/#!/1234" ) == 0 )
$next = true;
if ( $next &&
( strcasecmp( $item[ "tag" ],"g:id" ) == 0 ) )
{ echo $item[ "value" ];
break;
}
}
?>
刚刚更正了XML数据中的错误:标记</item> <item>
错误并且混淆了XML解析器,因此我将其替换为<item> </item>
(在您问题中的XML数据中间)。
如果先前有更改,如果搜索到值“http://www.website.com/#!/0987”,则会显示“这是我不需要的”。