我不使用simple_xml,但如果需要,使用DOMDocument 和DOMXPath 应该很容易移植到simple_xml。最初我以为您正在寻找 STOK_KODU 的子节点,但 XML 的结构表明并非如此。 XPath 查询将找到具有相关 $product_code 的节点,您可以从中轻松找到父节点,从而找到它的任何/所有子节点。
$file='http://xml.aksel.com.tr/Xml.aspx?SK=d021da08&CK=50288';
#$file='c:/temp/Xml.xml'; /* saved locally to test */
$output=array();
$product_code=13775;
$query='//XMLWEBDATA/STOK_KODU[ contains( text(), "'.$product_code.'" ) ]';
$dom=new DOMDocument;
$dom->load( $file );
$xp=new DOMXPath( $dom );
$col=$xp->query( $query );
if( $col && $col->length > 0 ){
foreach( $col as $node ){
/* get the parent */
$parent=$node->parentNode;
$data=array();
for( $i=0; $i < $parent->childNodes->length; $i++ ){
$tag=$parent->childNodes->item( $i )->tagName;
$value=$parent->childNodes->item( $i )->nodeValue;
if( !empty( $tag ) && !empty( $value ) ) $data[ $tag ]=$value;
}
$output[]=$data;
}
/* remove duplicates if there are any */
$output=array_unique( $output );
}
$xp = $dom = null;
/* process the results accordingly */
if( !empty( $output ) ){
foreach( $output as $obj ){
printf('<pre>%s</pre>', urldecode( http_build_query( $obj, null, PHP_EOL ) ) );
}
}
输出将是
STOK_KODU=13775
STOK_ADI=CHIP EPSON C3800 Black (S051127)
LISTEFIYAT=2,73
STOKBAKIYE1=16
GRUPKODU=DOLUM ÜRÜNLERİ GRUBU
KOD1=TONER DOLUM ÜRÜNLERİ
KOD2=ÇİPLER
PARABIRIMI=$
KULL5N=9500
RESIMURL=http://xml.aksel.com.tr/Photo.aspx?ID=22705&STOK=13775
将每个字段作为变量访问(我理解您的评论是这样的)
foreach( $col as $node ){
/* get the parent */
$parent=$node->parentNode;
$data=array();
for( $i=0; $i < $parent->childNodes->length; $i++ ){
try{
/* test node type to avoid errors */
if( $parent->childNodes->item( $i )->nodeType==XML_ELEMENT_NODE ){
$tag=$parent->childNodes->item( $i )->tagName;
$value=$parent->childNodes->item( $i )->nodeValue;
if( !empty( $tag ) && !empty( $value ) ) $data[ $tag ]=$value;
}
}catch( Exception $e ){
echo $e->getMessage();
continue;
}
}
$output[]=$data;
}
要作为变量访问,请使用extract
if( !empty( $output ) ){
foreach( $output as $obj ){
extract( $obj );
printf("<pre>%s\n%s\n%s</pre>", $STOK_KODU, $STOK_ADI, $GRUPKODU );
}
}